【发布时间】:2014-06-27 17:11:30
【问题描述】:
我正在使用以下代码将原始数据值转换为十六进制字符串,以便找到一些信息。但我得到了 FFFFFFFF 我应该得到 FF 的地方。
例如,结果应该是“FF 01 00 00 EC 00 00 00 00 00 00 00 00 00 E9”,但我得到的是“FFFFFFFFF 01 00 00 FFFFFFEC 00 00 00 00 00 00 00 00 00 FFFFFFE9”。
有人知道这里发生了什么吗?
std::vector<unsigned char> buf;
buf.resize( ANSWER_SIZE);
// Read from socket
m_pSocket->Read( &buf[0], buf.size() );
string result( buf.begin(), buf.end() );
result = ByteUtil::rawByteStringToHexString( result );
std::string ByteUtil::int_to_hex( int i )
{
std::stringstream sstream;
sstream << std::hex << i;
return sstream.str();
}
std::string ByteUtil::rawByteStringToHexString(std::string str)
{
std::string aux = "", temp = "";
for (unsigned int i=0; i<str.size(); i++) {
temp += int_to_hex(str[i]);
if (temp.size() == 1) {
aux += "0" + temp + " "; // completes with 0
} else if(i != (str.size() -1)){
aux += temp + " ";
}
temp = "";
}
// System.out.println(aux);
return aux;
}
更新:调试时,我注意到 int_to_hex 返回的是 FFFFFFFF 而不是 FF。我该如何解决?
【问题讨论】:
-
另外,您知道使用
std::istringstream会非常简单。 -
FFFFFF.. 表明您遇到了签名问题。如果一个 1 字节值的第一位是 '1',那么它就是一个负数,当你将它转换为一个 4 字节值(一个 int)时,它前面会有很多 F。
-
@JoachimPileborg 我按照他们的建议做了here,但我得到了相同的结果。我对 c++ 很陌生,我从 Java 中添加了上面的代码,它可以正常工作。
标签: c++ hex stdstring data-conversion