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
NealB Mar 16 '10 at 17:44 2010-03-16 17:44
source share