Joseph
Joseph

Reputation: 1774

Weird casting from string element

I get std:string which should include bytes (array of chars), I'm trying to display the bytes, but first byte always include weird data:

4294967169, how this can be a byte/char?!

void do_log(const std::string & data) {
std::stringstream ss;

ss<< "do_log: ";

int min = min((data.length()), (20)); // first 20 bytes

for (int i=0;i<min;i++)
{ 
    ss  << setfill ('0') << setw(2) << hex << (unsigned int)data.at(i) <<" ";
}

log(ss.str());
}

Data I log is: ffffff81 0a 53 3a 30 30 38 31 30 36 43 38

Why and how this ffffff81 appear? if the string.at should return char?

Upvotes: 0

Views: 109

Answers (2)

Christophe
Christophe

Reputation: 73386

When you write (unsigned int)data.at(i), data.at(i) is a char which then is submitted to integer promotion. If on your system char is signed, the values greater than 127 are interpreted as negative number. The sign bit will remain in the integer promotion, giving such strange results.

You can verify if char is signed by looking at numeric_limits<char>::is_signed

You can easily solve the issue by getting rid of the bits added by the integer promotion, by ANDing the integer with 0xff: (static_cast<int>(data.at(i)) & 0xff)

Another way is to force your compiler to work with unsigned chars. For example, with option -funsigned-char on gcc or /J with MSVC.

Upvotes: 3

Louis Newstrom
Louis Newstrom

Reputation: 172

string contains signed characters.
So a character 0x81 is interpreted as a negative number, like 0xFFFFFF81.
You cast this character to an unsigned int, so it becomes a very large number.

Upvotes: 1

Related Questions