如何使用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];
    }

}

编辑:

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

最佳答案

我认为向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);
}

这是强制将其打印为数字而不是您所看到的字符的必要条件。

关于c++ - 如何在cout/c++中编写此代码?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11765522/

10-11 23:21
查看更多