Unsigned with a negative value

See simple code below:

#include <iostream> #include <stdlib.h> using namespace std; int main(void) { unsigned long currentTrafficTypeValueDec; long input; input=63; currentTrafficTypeValueDec = (unsigned long) 1LL << input; cout << currentTrafficTypeValueDec << endl; printf("%u \n", currentTrafficTypeValueDec); printf("%ld \n", currentTrafficTypeValueDec); return 0; } 

Why does printf () display currentTrafficTypeValueDec (unsigned long) with a negative value?

Output:

 9223372036854775808 0 -9223372036854775808 
+5
c ++
Mar 16 '10 at 15:45
source share
6 answers

Fun with beats ...

cout prints the number as Unsigned Long, all 64 bits are significant and printed as unsigned binary integer (I think the format here will be %lu ).

printf(%u ... treats the input as a normal unsigned integer (32 bits?). This causes bits 33 through 64 to be dropped - leaving zero.

printf(%ld ... treats the input as a 64-bit signed number and simply prints it as such.

What may seem confusing in the last printf is that it gives the same absolute value as cout , but with a minus sign. When viewed as an unsigned integer, all 64 bits are important for creating an integer value. However, for signed numbers, bit 64 is a sign bit. When a character bit is set (as in your example), it indicates that the remaining 63 bits should be treated as a negative number, represented in 2 compliment . Positive numbers are printed simply by converting their binary value to decimal. However, for a negative number, the following happens: Print a negative sign, XOR bits 1 through 63 with binary “1” bits, add 1 to the result, and print the unsigned value. Dropping the sign bit (bit 64), you get 63 '0' bits, XORing with '1' bits gives you 63 '1' bits, adds +1, and the whole thing collapses to give you an unsigned integer that has bit 64 set to '1' and the rest to '0' - this is the same as what you received with cout BUT, as a negative number.

Once you have found out why the above explanation is correct, you should also be able to understand from this

+3
Mar 16 '10 at 17:44
source share
— -

%d is a signed formatter. Re-interpretation of the currentTrafficTypeValueDec bit (from 2 to 63rd power), since a signed long gives a negative value. Therefore printf() prints a negative number.

Perhaps you want to use %lu ?

+17
Mar 16 '10 at 15:48
source share

You lied to printf, passing it an unsigned value, while the format specification said it would be signed.

+13
Mar 16 '10 at 15:48
source share

Since you move 1 to the sign bit of the variable. When you print it as a sign value, it is negative.

+5
Mar 16 '10 at 15:51
source share

a variable does not carry its own type. You tell printf its type. Try:

 printf("%lu \n", currentTrafficTypeValueDec); 

because ld meand long signed is wrong.

+1
Mar 16 '10 at 15:50
source share

You are typing %ld or a long decimal point. That is why it returns a negative value.

0
Mar 16
source share



All Articles