c++ - Wrong values in raw data to hex string convertion? -
i using following code convert raw data values hexstring can find information. getting ffffffff supposed ff.
for example, result should "ff 01 00 00 ec 00 00 00 00 00 00 00 00 00 e9", getting "fffffffff 01 00 00 ffffffec 00 00 00 00 00 00 00 00 00 ffffffe9".
does know happening here?
std::vector<unsigned char> buf; buf.resize( answer_size); // read 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 ) { std::stringstream sstream; sstream << std::hex << i; return sstream.str(); } std::string byteutil::rawbytestringtohexstring(std::string str) { std::string aux = "", temp = ""; (unsigned int i=0; i<str.size(); i++) { temp += int_to_hex(str[i]); if (temp.size() == 1) { aux += "0" + temp + " "; // completes 0 } else if(i != (str.size() -1)){ aux += temp + " "; } temp = ""; } // system.out.println(aux); return aux; }
update: debugging, noticed int_to_hex returning ffffffff instead of ff. how can fix that?
note use of unsigned
instead of int
in int_to_hex()
.
#include <iostream> #include <sstream> std::string int_to_hex(unsigned i) { std::stringstream sstream; sstream << std::hex << i; return sstream.str(); } int main() { std::cout << int_to_hex(0xff) << "\n"; }
output
[1:58pm][wlynch@watermelon /tmp] ./foo ff
additionally...
we can see in question looking at, static_cast achieve same result.
ss << std::setw(2) << static_cast<unsigned>(buffer[i]);
Comments
Post a Comment