Search code examples
cbitsignuint32-t

Bit sign of uint32_t -1 instead of 1 in C


I have done

uint32_t bits= 0;

bits |= 1<< 31;

and then using

void printbits(uint32_t n) {
    if (n) {
        printbits(n >> 1);
        printf("%d", n & 1);
    }
}

on bits I get 10000000000000000000000000000000, which is what I want, but when I use my getbit(bits, 0)

int get_bit(int n, int bitnr) {
    int mask = 1 << bitnr;
    int masked_n = n & mask;
    int thebit = masked_n >> bitnr;
    return thebit;
}

I get a -1 instead of 1, any idea why?

Thank's!


Solution

  • Right Shifting a signed number and if the number is negative is implementation behavior.

    According to the Section 6.5.7 of the latest draft standard, this behavior on negative numbers is implementation dependent:

    The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an 
    unsigned type or if E1 has a signed type and a nonnegative value, the value of 
    the result is the integral part of the quotient of E1 / 2E2. If E1 has a signed
    type and a negative value, the resulting value is implementation-defined.
    

    Edit: Please do refer, how a number is represented here https://stackoverflow.com/a/16728502/1814023