Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"unsigned int" prints as a negative number?

Tags:

objective-c

I am taking an integer, in this case 192, and left shifting it 24 spaces. The leading 1 is causing it to become negative, it seems.

unsigned int i = 192;
unsigned int newnumber = i << 24;
NSLog(@"newnumber is %d",newnumber);

I am expecting 3,221,225,472 but I get -1,073,741,824 (commas added for clarity)

An unsigned integer shouldn't be negative right?

like image 903
Michael Avatar asked Apr 22 '12 23:04

Michael


1 Answers

Because you reinterpret it in NSLog as a signed integer. You should use %u to see an unsigned value.

There is no way for a function with variable number of arguments to know with certainty the type of the value that you pass. That is why NSLog relies on the format string to learn how many parameters you passed, and what their types are. If you pass a type that does not match the corresponding format specifier, NSLog will trust the specifier and interpret your data according to it. Modern compilers may even warn you about it.

like image 149
Sergey Kalinichenko Avatar answered Sep 27 '22 17:09

Sergey Kalinichenko