How do I get the lower 8 bits of an int?
Lets say I have an int variable n = 8. On most machines this will be a 32 bit value. How can I only get the lower 8 bits (lowest byte) of this in binary? Also how can I access each bit to find o开发者_StackOverflow社区ut what it is?
unsigned n = 8;
unsigned low8bits = n & 0xFF;
Note a few things:
- For bitwise operations, always use the
unsigned
types - Bits can be extracted from numbers using binary masking with the
&
operator - To access the low 8 bits the mask is
0xFF
because in binary it has its low 8 bits turned on and the rest 0 - The low 8 bits of the number 8 are... 8 (think about it for a moment)
To access a certain bit of a number, say the k
th bit:
unsigned n = ...;
unsigned kthbit = (1 << k) & n;
Now, kthbit
will be 0 if the k
th bit of n
is 0, and some positive number (2**k
) if the k
th bit of n
is 1.
Use bitwise arithmetic to mask off the lowest 8 bits:
unsigned char c = (x & 0xFF);
To access the nth lowest bit, the equation is (x & (1 << n))
(n of zero indicates the least significant bit). A result of zero indicates the bit is clear, and non-zero indicates the bit is set.
The best way is to use the bit logical operator & with the proper value.
So for the lower 8 bits:
n & 0xFF; /* 0xFF == all the lower 8 bits set */
Or as a general rule:
n & ((1<<8)-1) /* generate 0x100 then subtract 1, thus 0xFF */
You can combine with the bit shift operator to get a specific bit:
(n & (1<<3))>>3;
/* will give the value of the 3rd bit - note the >>3 is just to make the value either 0, or 1, not 0 or non-0 */
You can test if a particular bit is set in a number using << and &, ie:
if (num & (1<<3)) ...
will test if the fourth bit is set or not.
Similarly, you can extract just the lowest 8 bits (as an integer) by using & with a number which only has the lowest 8 bits set, ie num & 255
or num & 0xFF
(in hexadecimal).
精彩评论