How to find if the MSB or the LSB is set?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
| #include "stdio.h"
#include "limits.h"
/* This creates a 32 bit value with only MSB set
* 1 << 31 times produces 10000000000000000000000000000000 i.e. 0x80000000
* And then we AND it with x which will either yield 0x80000000 or 0x0
* !!(0x80000000) = 1 and !!(0x0) = 0
*/
static unsigned short is_set_MSB(unsigned int x)
{
return !!((1<<(sizeof(unsigned int) * CHAR_BIT - 1)) & x);
}
/* This is straight forward, x & 1 will either yield 1 or 0 directly.
*/
static unsigned short is_set_LSB(int x)
{
return (x & 1);
}
int main(int argc, char **argv)
{
printf("%08x - %d \n", 0xffffffff, is_set_LSB(0xffffffff));
printf("%08x - %d \n", 0xfffffff0, is_set_LSB(0xfffffff0));
printf("%08x - %d \n", 0xffffffff, is_set_MSB(0xffffffff));
printf("%08x - %d \n", 0x0fffffff, is_set_MSB(0x0fffffff));
return 0;
}
|
[root@Imperfecto_1 ~]# gcc -g run.c && ./a.out
ffffffff - 1
fffffff0 - 0
ffffffff - 1
0fffffff - 0
No comments:
Post a Comment