How to go through each bit of a byte
I do not not know how to implement the following algorithm.
For example I have int=26, this is "11010" in binary. Now I need to implement one operation 开发者_开发百科for 1, another for 0, from left to right, till the end of byte. But I really have no idea how to implement this. Maybe I can convert binary to char array, but I do not know how. btw, int equals 26 only in the example, in the application it will be random.
Since you want to move from 'left to right':
unsigned char val = 26; // or whatever
unsigned int mask;
for (mask = 0x80; mask != 0; mask >>= 1) {
if (val & mask) {
// bit is 1
}
else {
// bit is 0
}
}
The for
loop just walks thorough each bit in a byte, from the most significant bit to the least.
I use this option:
isBitSet = ((bits & 1) == 1);
bits = bits >> 1
I find the answer also in stackoverflow:
How do I properly loop through and print bits of an Int, Long, Float, or BigInteger?
You can use modulo arithmetic or bitmasking to get what you need.
Modulo arithmetic:
int x = 0b100101;
// First bit
(x >> 0) % 2; // 1
// Second bit
(x >> 1) % 2; // 0
// Third bit
(x >> 2) % 2; // 1
...
etc.
Bitmasking
int x = 0b100101;
int mask = 0x01;
// First bit
((mask << 0) & x) ? 1 : 0
// Second bit
((mask << 1) & x) ? 1 : 0
...
etc.
In C, C++, and similarly-syntaxed languages, you can determine if the right-most bit in an integer i
is 1 or 0 by examining whether i & 1
is nonzero or zero. (Note that that's a single &
signifying a bitwise AND operation, not a &&
signifying logical AND.) For the second-to-the-right bit, you check i & 2
; for the third you check i & 4
, and so on by powers of two.
More generally, to determine if the bit that's j
th from the right is zero, you can check whether i & (1 << (j-1)) != 0
. The <<
indicates a left-shift; 1 << (j-1)
is essentially equivalent to 2j-1.
Thus, for a 32-bit integer, your loop would look something like this:
unsigned int i = 26; /* Replace this with however it's actually defined. */
int j;
for (j = 31; j >= 0; j--)
{
if ((i & (1 << (j-1))) != 0)
/* do something for jth bit is 1 */
else
/* do something for jth bit is 0 */
}
Hopefully, that's enough to get you started.
Came across a similar problem so thought I'd share my solution. This is assuming your value is always one byte (8 bits)
Iterate over all 8 bits within the byte and check if that bit is set (you can do this by shifting the bit we are checking to the LSB position and masking it with 0x01
)
int value = 26;
for (int i = 0; i < 8; i++) {
if ((value >> i) & 0x01) {
// Bit i is 1
printf("%d is set\n", i);
}
else {
// Bit i is 0
printf("%d is cleared\n", i);
}
}
I'm not exactly sure what you say you want to do. You could probably use bitmasks to do any bit-manipulation in your byte, if that helps.
Hi Look up bit shifting and bitwise and.
精彩评论