2
votes

I am using Qt, and I have an unsigned char *bytePointer and want to print out a number-value of the current byte. Below is my code, which is meant to give the int-value and the hex-value of the continuous bytes that I receive from a machine attached to the computer:

int byteHex=0;
byteHex = (int)*bytePointer;

qDebug << "\n  int: " //this is the main issue here. 
          << *bytePointer;

std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")\n";

}

This gives perfect results, and I get actual numbers, however this code is going into an API and I don't want to use Qt-only functions, such as qDebug. So when I try this:

int byteHex=0;
byteHex = (int)*bytePointer;

std::cout << "\n  int: " //I changed qDebug to std::cout
          << *bytePointer;

std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")\n";

}

The output does give the hex-values perfectly, however the int-values return symbols (like ☺, └, §, to list a few).

My question is: How do I get std::cout to give the same output as qDebug?

EDIT: for some reason the symbols only occur with a certain Qt setting. I have no idea why it happened but it's fixed now.

2
Note that this will work once, then cout is stuck in hex mode because you don't reset it.Sebastian Redl
Is it a Qt application? If yes, why not qDebug? If not, why did you use it earlier at all?lpapp
@SebastianRedl that was the problem, actually. I just didn't add std::dec afterwards. I'm pretty embarrassed, but thank you!Admin Voter
@lpapp Right now it is in Qt, but I am now moving it to Visual Studio, because it's part of an API.Admin Voter
There are tricks and you could also use qInstallMsgHandler. There is even a Qt plugin for Visual Studio both Qt 4 as well as Qt 5. What problem exactly are you facing?lpapp

2 Answers

2
votes

As others pointed out in comment, you change the outputting to hex, but you do not actually set it back here:

std::cout << " (hex:  "
          << std::hex
          << byteHex
          << ")\n";

You will need to apply this afterwards:

std::cout << std::dec;
1
votes

Standard output streams will output any character type as a character, not a numeric value. To output the numeric value, convert to a non-character integer type:

std::cout << int(*bytePointer);