对于char型,它所表示的范围为-128~+127,假设有如下语句:

char data[3] = {0xab, 0xcd, 0xef}; 

初始化之后想打印出来,cout << data[0] << data[1] << data[2]; 发现都是乱码,没有按十六进制输出。

在ASCII中,一共定义了128个字符,其中33个无法显示,为0~31和127,32到126为可显示字符,当使用cout输出一个char型字符时,如果是可显示范围内,则输出相应可显示字符,其余的都输出乱码。

如果我们要使字符按十六进制输出,可以使用hex,但是发现cout << hex << data[0];没有输出十六进制,因为hex只对整数起作用,将data[0]转换为int,cout << hex << int(data[0]); 发现输出的结果前面带了很多f。因为data[0]是有符号数,最高位为1时,转换为int时,其余位都为1,cout << hex << (unsigned int) (unsigned char)data[0];结果正确。

对于小于16的char,输出只显示一位,如果希望都显示两位,可以在输出前设置cout << setfill('0') << setw(2);

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    std::cout << "Hello World!\n";
    char n = 222;
    cout << hex << setfill('0') << setw(2) << (unsigned int)(unsigned char)(n)<<endl;
    cout << hex << setfill('0') << setw(2) << (int)n;
}

 

输出到文件:

#include <iostream>

#include <cstdio>#include <fstream>
 
using namespace std;
 ofstream file;

    file.open("commands_.log",
              std::ios_base::trunc );

    auto data = playback->serialize();
    //file.write(data->data(), data->size());

  {
       
      int len = data->size();
      const char* c = static_cast<const char*>(data->data());

      for (int i = 0; i < len;) {
        file << ",0x" << hex << setfill('0') << setw(2)
             << (unsigned int)(unsigned char)c[i];
        i++;
        if (i % 16 == 0)
          file << endl;
      }
    } 


  }

 

相关文章: