Visual C ++:尝试将二进制转换为ascii值

时间:2014-03-20 05:14:42

标签: c++ c++-cli

我的二进制到ASCII转换有问题我所做的是我有一些文本框,我试图将二进制值放入该文本框并将这些值传递给如下所示的函数:

System::String^ conversion(const char* input)
{
     int length = strlen(input);     //get length of string
 int binary[8];    //array used to store 1 byte of binary number (1 character)
 int asciiNum = 0;      //the ascii number after conversion from binary
 System::String^ ascii;      //the ascii character itself

     int z = 0;   //counter used

 for(int x = 0; x < length / 8; x++)     //reading in bytes. total characters 
 {
     for(int a = 0; a < 8; a++)      //store info into binary[0] through binary[7]
     {
     binary[a] = (int) input[z] - 48;      //z never resets
     z++;
     }

  int power[8];    //will set powers of 2 in an array
  int counter = 7;        //power starts at 2^0, ends at 2^7
  for(int x = 0; x < 8; x++)
  {
      power[x] = counter;      //power[] = {7, 6, 5, ..... 1, 0}
      counter--;    //decrement counter each time
  }

  for(int y = 0; y < 8; y++)    //will compute asciiNum
  {
      double a = binary[y];    //store the element from binary[] as "a"
      double b = power[y];    //store the lement from power[] as "b"

      asciiNum += a* pow(2, b);   
  }
  ascii = System::Convert::ToString(asciiNum);  

  asciiNum = 0;    //reset asciiNum for next loop
  return ascii;
}               
 }

问题是我只获取ASCII值而无法获取相关字符。我希望那个角色能帮助我。提前完成。

2 个答案:

答案 0 :(得分:0)

可以将整数打印为字符。您可以将整数重新转换为字符,而不是使用ToString:

(char)asciiNum

示例:

#include <iostream.h>
using namespace std;
int main ()
{
int beta=100;
cout<<"Value of integer is: "<<beta<<endl;
cout <<"Value of char is: "<<(char) beta<<endl;

}

结果:

Value of integer is : 100

Value of char is : d

答案 1 :(得分:0)

char asciichar=(unsigned char) asciinum;

这会将您的号码转换为ascii字符,您可以将结果返回char而不是std::string