I've been reading many suggestions on the same topic, and tried to implement many of them, but it seems that none of them is actually working in my environment. I'm using QT 5, but I think the problem is not related to QT but to how the hexadecimal character 0x00 is interpreted by the language. What I have to achieve is to display a stream of unsigned char as hexadecimal values, eg:
Input bytes: 0x00 0x4E 0x01 0x00 0x17 0x00
Display as: 0x00:0x4E:0x01:0x00:0x17:0x00
it seems quite easy, but all I get is an empty string...
The functions I wrote:
QString getBufferAsHexStr(const unsigned char* buf, int buffsize) {
std::string finalstring("");
char tempbuff[5];
int n=0, index=0;
for (int c = 0; c < buffsize; c++) {
if(c == buffsize-1) {
n=sprintf(tempbuff, "0x%02X", buf[c]);
} else {
n=sprintf(tempbuff, "0x%02X:", buf[c]);
}
finalstring.append(tempbuff, n);
index += n;
}
QString resultStr(finalstring.c_str());
return resultStr;
}
QString getBufferAsHexStr(const unsigned char* buf, int buffsize) {
std::stringstream ss;
for (int c = 0; c < buffsize; c++) {
if(c == buffsize-1) {
ss << std::hex << std::showbase << buf[c];
} else {
ss << std::hex << std::showbase << buf[c] << ":";
}
}
const std::string finalstring = ss.str();
QString resultStr(finalstring.c_str());
return resultStr;
}
tempbuffin your first example have a size equal to what you think it should be? You're walking a tightrope by making this size5. Why not make it 10 and be safe? As a matter of fact, it is a buffer overrun, since you're trying to stuff 6 characters into it.std::string?std::string, this code shows no issue. Also, your original code with a buffer of 5 crashes the program created with Visual Studio with a corruption error (debug build).0x%02X:You have 5 visible characters ("0x" + 2 hex characters + 1 colon) == 5) plus the terminating\0, making this 6 characters.