【问题标题】:How to print byte array in hexadecimal - c++ [duplicate]如何以十六进制打印字节数组-c ++ [重复]
【发布时间】:2021-02-25 04:40:50
【问题描述】:

我这里有一段代码:

#include <iostream>
#include <iomanip>
using namespace std;

int main(void)
{
  
  
  unsigned char bytes[] = {0x43,0x4d,0x30,0x30,0x0f,0x0D};
  
  std::cout << std::hex << bytes[0] <<std::endl;
  

}

上面的程序正在将 C 打印到命令行。 如何使程序将 43 打印到命令行。 我的操作系统是 Windows 10,64 位。

【问题讨论】:

  • 使用&lt;&lt; 打印的任何char 值都将作为字符打印。您需要将该值转换为非char 整数类型。例如int.
  • static_cast(bytes[0])
  • 除非您需要将数组传递给需要字节数组(或短裤)的函数,否则使用较小的整数类型确实没有用。请改用int(或unsigned)。
  • @RetiredNinja static_cast(bytes[0]) 有效。
  • @RetiredNinja 不完全是。

标签: c++ arrays cout


【解决方案1】:

使用 printf 函数:

#include<cstdio>
...
printf("%x", bytes[0]);

如果您想了解有关 printf 函数的更多信息,请参阅here

【讨论】:

  • @RetiredNinja static_cast(bytes[0]) 也可以。
  • (int)(bytes[0]) 也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2013-01-18
  • 2012-05-22
  • 2017-12-26
  • 2013-11-30
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多