Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

working with char binary brings unexpected results

Tags:

c++

byte

I have file where from I reading the first char - meaning the first 8 bits. That is exactly what I want. My code:

char content;
char * pcontent = &content;

src_f.read(pcontent, 1);
cout << (int)content << endl; //prints -62
cout << (unsigned int)content << endl; //prints 4294967234

But: I do understand the -62. Integer can store minus values, but where did the 4294967234 come from?? I would expect some plus number smaller than 256 (because of max 8 bits..). Could you please clarify that for me?

Thx!

like image 249
tsusanka Avatar asked Feb 25 '23 20:02

tsusanka


1 Answers

When you cast the content variable to an (int) or (unsigned int), you're converting it to a data type that is 32 bits wide. So the byte that you're reading in (which appears to be equal to 11000010 in binary) turns into 11111111 11111111 11111111 11000010. When this is read as an int, it equals -62, when read as an unsigned int, it equals 4294967234

like image 200
Sean Avatar answered Mar 04 '23 12:03

Sean