Reading the value of 31st bit of a 32bit integer

0

For reading the 31th bit(MSB) of a 32bit integer one method is as below

int main(int argc, char *argv[]) {
    int b =0x80005000;
    if(b&(1<<31))
        printf("bit is one\n");
    else
        printf("bit is zero\n");
return 0;
}

My question is, is there any other optimum method to do this with less instruction cycles?

c
gcc
arm
asked on Stack Overflow Jan 28, 2017 by rahul_T_T

1 Answer

3

In two's complement representation, the MSB is set when the number is negative and clear when the number is non-negative, so this would also work.

int b = 0x80005000;
if (b < 0)
    printf("bit is one\n");
else
    printf("bit is zero\n");

In fact, for the if(b&(1<<31)) code you wrote, GCC does produce assembly that compares to 0 and checks the sign - identical to the output that GCC generates on this code.

answered on Stack Overflow Jan 28, 2017 by ephemient

User contributions licensed under CC BY-SA 3.0