字符数组到十六进制字符串 C++
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10723403/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Char array to hex string C++
提问by Roman
I searched char*
to hex
string before but implementation I found adds some non-existent garbage at the end of hex
string. I receive packets from socket, and I need to convert them to hex
strings for log (null-terminated buffer). Can somebody advise me a good implementation for C++
?
我之前搜索char*
过hex
字符串,但我发现实现在hex
字符串的末尾添加了一些不存在的垃圾。我从套接字接收数据包,我需要将它们转换hex
为日志字符串(空终止缓冲区)。有人可以建议我一个好的实现C++
吗?
Thanks!
谢谢!
回答by Jorge González Lorenzo
Supposing data is a char*. Working example using std::hex:
假设数据是一个字符*。使用 std::hex 的工作示例:
for(int i=0; i<data_length; ++i)
std::cout << std::hex << (int)data[i];
Or if you want to keep it all in a string:
或者,如果您想将其全部保存在一个字符串中:
std::stringstream ss;
for(int i=0; i<data_length; ++i)
ss << std::hex << (int)data[i];
std::string mystr = ss.str();
回答by K-ballo
Here is something:
这里有一些东西:
char const hex_chars[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
for( int i = data; i < data_length; ++i )
{
char const byte = data[i];
string += hex_chars[ ( byte & 0xF0 ) >> 4 ];
string += hex_chars[ ( byte & 0x0F ) >> 0 ];
}
回答by demi
The simplest:
最简单的:
int main()
{
const char* str = "hello";
for (const char* p = str; *p; ++p)
{
printf("%02x", *p);
}
printf("\n");
return 0;
}
回答by Tomas
Code snippet above provides incorrect byte order in string, so I fixed it a bit.
上面的代码片段在字符串中提供了不正确的字节顺序,所以我修复了它。
char const hex[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B','C','D','E','F'};
std::string byte_2_str(char* bytes, int size) {
std::string str;
for (int i = 0; i < size; ++i) {
const char ch = bytes[i];
str.append(&hex[(ch & 0xF0) >> 4], 1);
str.append(&hex[ch & 0xF], 1);
}
return str;
}
回答by Alexei Martianov
I've found good example here Display-char-as-Hexadecimal-String-in-C++:
我在这里找到了很好的例子Display-char-as-Hexadecimal-String-in-C++:
std::vector<char> randomBytes(n);
file.read(&randomBytes[0], n);
// Displaying bytes: method 1
// --------------------------
for (auto& el : randomBytes)
std::cout << std::setfill('0') << std::setw(2) << std::hex << (0xff & (unsigned int)el);
std::cout << '\n';
// Displaying bytes: method 2
// --------------------------
for (auto& el : randomBytes)
printf("%02hhx", el);
std::cout << '\n';
return 0;
Method 1 as shown above is probably the more C++ way:
Cast to an unsigned int
Usestd::hex
to represent the value as hexadecimal digits
Usestd::setw
andstd::setfill
from<iomanip>
to format
Note that you need to mask the cast int against0xff
to display the least significant byte:(0xff & (unsigned int)el)
.Otherwise, if the highest bit is set the cast will result in the three most significant bytes being set to
ff
.
如上所示的方法1可能是更多的C++方式:
Cast to an unsigned int
用于std::hex
将值表示为十六进制数字
使用std::setw
和std::setfill
from<iomanip>
格式化
请注意,您需要屏蔽 cast int0xff
以显示最低有效字节:(0xff & (unsigned int)el)
。否则,如果设置了最高位,则转换将导致三个最高有效字节设置为
ff
。
回答by Marek R
Using boost:
使用提升:
#include <boost/algorithm/hex.hpp>
std::string s("tralalalala");
std::string result;
boost::algorithm::hex(s.begin(), s.end(), std::back_inserter(result));
回答by SpongeBob the codder
You can try this code for converting bytes from packet to a null-terminated string and store to "string" variable for processing.
您可以尝试使用此代码将字节从数据包转换为以空字符结尾的字符串并存储到“字符串”变量进行处理。
const int buffer_size = 2048;
// variable for storing buffer as printable HEX string
char data[buffer_size*2];
// receive message from socket
int ret = recvfrom(sock, buffer, sizeofbuffer, 0, reinterpret_cast<SOCKADDR *>(&from), &size);
// bytes converting cycle
for (int i=0,j=0; i<ret; i++,j+=2){
char res[2];
itoa((buffer[i] & 0xFF), res, 16);
if (res[1] == 0) {
data[j] = 0x30; data[j+1] = res[0];
}else {
data[j] = res[0]; data[j + 1] = res[1];
}
}
// Null-Terminating the string with converted buffer
data[(ret * 2)] = 0;
When we send message with hex bytes 0x01020E0F, variable "data" had char array with string "01020e0f".
当我们发送带有十六进制字节 0x01020E0F 的消息时,变量“data”有一个带有字符串“01020e0f”的字符数组。