我怎么用cout/c ++写这个?

mis*_*ter 1 c++ string hex cout

我如何用cout编写以下函数?我的主要目的是在知道如何将其与cout一起使用后,实际将所有值打印到文件中.std :: hex不起作用!

void print_hex(unsigned char *bs, unsigned int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        printf("%02x", bs[i]);
        //Below does not work
        //std::cout << std::hex << bs[i];
    }

}
Run Code Online (Sandbox Code Playgroud)

编辑:

cout打印出如下值:r9 {èZ[ôÃ

Fle*_*exo 7

我认为向int添加一个强制转换器会做你想要的:

#include <iostream>
#include <iomanip>

void print_hex(unsigned char *bs, unsigned int n)
{
    int i;
    for (i = 0; i < n; i++)
    {
        std::cout << std::hex << static_cast<int>(bs[i]);
    }

}

int main() {
  unsigned char bytes[] = {0,1,2,3,4,5};
  print_hex(bytes, sizeof bytes);
}
Run Code Online (Sandbox Code Playgroud)

这需要强制它作为数字打印,而不是你所看到的字符.

  • 可能有必要改为使用`std :: cout << std :: setw(2)<< std :: setfill('0')<< std :: hex`来获得小于16的整数所需的行为. (4认同)