简体   繁体   English

如何将char数组转换为十六进制值列表?

[英]How to convert a char array to a list of HEX values?

Would I would like to be able to do is convert a char array (may be binary data) to a list of HEX values of the form: ab 0d 12 f4 etc.... 我想做的是将一个char数组(可能是二进制数据)转换为以下形式的HEX值列表:ab 0d 12 f4等。

I tried doing this with 我尝试这样做

lHexStream << "<" << std::hex << std::setw (2) << character << ">"; lHexStream <<“ <” << std :: hex << std :: setw(2)<<字符<<“>”;

but this did not work since I would get the data printing out as: 但这不起作用,因为我将数据打印为:

<ffe1><2f><ffb5><54>< 6><1b><27><46><ffd9><75><34><1b><ffaa><ffa2><2f><ff90><23><72><61><ff93><ffd9><60><2d><22><57>

Note here that some of the values would have 4 HEX values in them? 注意这里的某些值中会有4个十六进制值吗? eg 例如

What I would be looking for is what they have in wireshark, where they represent a char aray (or binary data) in a HEX format like: 我要寻找的是它们在wireshark中所拥有的,它们以十六进制格式表示字符格式(或二进制数据),例如:

08 0a 12 0f 08 0a 12 0f

where each character value is represented by just 2 HEX characters of the form shown above. 其中每个字符值仅由上述形式的2个十六进制字符表示。

It looks like byte values greater than 0x80 are being sign-extended to short (I don't know why it's stopping at short, but that's not important right now). 看起来大于0x80的字节值正被符号扩展为short(我不知道为什么它会在short停止,但这现在并不重要)。 Try this: 尝试这个:

IHexStream << '<' << std::hex << std::setw(2) << std::setfill('0')
           << static_cast<unsigned int>(static_cast<unsigned char>(character))
           << '>';

You may be able to remove the outer cast but I wouldn't rely on it. 也许可以删除外部演员表,但我不会依靠它。

EDIT: added std::setfill call, which you need to get <06> instead of < 6>. 编辑:添加了std :: setfill调用,您需要获取<06>而不是<6>。 Hat tip to jkerian; 给jkerian的帽子小费; I hardly ever use iostreams myself. 我自己几乎从未使用过iostream。 This would be so much shorter with fprintf: 使用fprintf会短得多:

fprintf(ihexfp, "<%02x>", (unsigned char)character);

As Zack mentions, The 4-byte values are because it is interpreting all values over 128 as negative (the base type is signed char), then that 'negative value' is extended as the value is expanded to a signed short. 正如Zack所提到的,4字节值是因为它将超过128的所有值都解释为负数(基本类型是带符号的char),然后当该值扩展为带符号的short时,“负值”被扩展。

Personally, I found the following to work fairly well: 就个人而言,我发现以下各项工作得相当不错:

char *myString = inputString;
for(int i=0; i< length; i++)
    std::cout << std::hex << std::setw(2) << std::setfill('0') 
              << static_cast<unsigned int>(myString[i]) << " ";

I think the problem is that the binary data is being interpreted as a multi-byte encoding when you're reading the characters. 我认为问题在于,在读取字符时,二进制数据被解释为多字节编码。 This is evidenced byt he fact that each of the 4-character hex codes in your example have the high bit set in the lower byte. 这可以通过以下事实证明:您的示例中每个4个字符的十六进制代码在低字节中都设置了高位。

You probably want to read the binary stream in ascii mode. 您可能想以ascii模式读取二进制流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM