I am using the following code to convert the raw data values to a hexstring so I can find some information. But I am getting FFFFFFFF where I was supposed to get FF.
For example, the result should be "FF 01 00 00 EC 00 00 00 00 00 00 00 00 00 E9", but I am getting "FFFFFFFFF 01 00 00 FFFFFFEC 00 00 00 00 00 00 00 00 00 FFFFFFE9".
Does anyone know what is happening here?
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;
}
UPDATE: Debugging, I noticed that the int_to_hex is returning FFFFFFFF instead of FF. How can I fix that?
Note the 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";
}
[1:58pm][wlynch@watermelon /tmp] ./foo
ff
We also can see in the question you are looking at , that they do a static_cast to achieve the same result.
ss << std::setw(2) << static_cast<unsigned>(buffer[i]);
OK Guys, sorry for the delay, I ran into the weekend and had some FIFA World Cup games to watch.
I was getting the same result no matter the change I made, so I decided to make some changes in the code before and I switched the input param from
std::string ByteUtil::rawByteStringToHexString(std::string str)
to
std::string ByteUtil::rawByteStringToHexString(vector<unsigned char> v)
and also kept the changes suggested by @sharth. Now I am getting the correct result.
Thank you all for the help!!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.