如何以十六进制而不是ASCII符号显示实际值

时间:2022-05-20 11:46:33
int main()
{
   char B[76]={0};

   ifstream infile;
   infile.open("tworecords.dat", ios::binary);
   infile.read(reinterpret_cast<char*>(B), sizeof (B));

   cout << "Array B in hex" << endl;

   for (int i = 0; i < 76; i++)
   {
      cout << hex << B[i] << " " << endl;;
   }

   return 0;


}

right now it reads the data correctly, but prints out the values as ASCII symbols. I would like to output the actual hex values in the file.

现在它正确读取数据,但将值打印为ASCII符号。我想在文件中输出实际的十六进制值。

example:

01 3D 76 D6 etc.

01 3D 76 D6等

2 个解决方案

#1


4  

Cast it to integer:

将其转换为整数:

cout << hex << static_cast<int>(B[i]) << " " << endl;

Or alternatively, if you don't want to cast, just add 0:

或者,如果你不想演员,只需加0:

cout << hex << B[i]+0 << " " << endl;

However you probably also want to make sure that for values below 16, a leading 0 is printed (e.g. for the newline character 0A, not just A):

但是,您可能还希望确保对于低于16的值,打印前导0(例如,对于换行符0A,而不仅仅是A):

cout << setfill('0') << setw(2) << hex << B[i]+0 << " " << endl;

#2


0  

You simply cast the number to an integer:

您只需将数字转换为整数:

cout << hex << (int)B[i] << " " << endl;

the <iostream> library (actually, all stream libraries) output ascii values for char types.

库(实际上,所有流库)输出char类型的ascii值。

#1


4  

Cast it to integer:

将其转换为整数:

cout << hex << static_cast<int>(B[i]) << " " << endl;

Or alternatively, if you don't want to cast, just add 0:

或者,如果你不想演员,只需加0:

cout << hex << B[i]+0 << " " << endl;

However you probably also want to make sure that for values below 16, a leading 0 is printed (e.g. for the newline character 0A, not just A):

但是,您可能还希望确保对于低于16的值,打印前导0(例如,对于换行符0A,而不仅仅是A):

cout << setfill('0') << setw(2) << hex << B[i]+0 << " " << endl;

#2


0  

You simply cast the number to an integer:

您只需将数字转换为整数:

cout << hex << (int)B[i] << " " << endl;

the <iostream> library (actually, all stream libraries) output ascii values for char types.

库(实际上,所有流库)输出char类型的ascii值。