尝试将二进制值转换为ascii值

c++ cli - Visual C++ : trying to convert binary to ascii value

本文关键字:转换 ascii 二进制      更新时间:2023-10-16

我有二进制到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值,不能得到相关字符。我想要那个角色,谁来帮我。

char asciichar=(unsigned char) asciinum;

这将把你的数字转换为ascii字符,你可以返回结果为char而不是std::string

可以将整数作为字符打印。除了使用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