Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unsigned long with negative value

Tags:

c++

Please see the 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 printf() displays the currentTrafficTypeValueDec (unsigned long) with negative value?

The output is:

9223372036854775808
0
-9223372036854775808 
like image 214
user292167 Avatar asked Mar 16 '10 15:03

user292167


2 Answers

%d is a signed formatter. Reinterpreting the bits of currentTrafficTypeValueDec (2 to the 63rd power) as a signed long gives a negative value. So printf() prints a negative number.

Maybe you want to use %lu?

like image 50
Mike DeSimone Avatar answered Sep 29 '22 19:09

Mike DeSimone


You lied to printf by passing it an unsigned value while the format spec said it would be a signed one.

like image 29
AProgrammer Avatar answered Sep 29 '22 20:09

AProgrammer