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?
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.
User contributions licensed under CC BY-SA 3.0