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.
You can do this. int x= inputBuffer[1]; bit1 = ((x>>7)&1==1); bit2 = ((x>>6)&1==1); bit3 = ((x>>5)&1==1); bit4 = ((x>>4)&1==1); bit5 = ((x>>3)&1==1); bit6 = ((x>>2)&1==1); bit7 = ((x>>1)&1==1); bit8 = (x&1==1);
For accessing a specific bit, you can use Shift Operators . If it is always a 1 that you are going to reset, then you could use an & operation. But, if it can also take 0 value, then & operation will fail as 0 & 1 = 0 . You could use | (OR) during that time.
A byte is a group of 8 bits. A bit is the most basic unit and can be either 1 or 0. A byte is not just 8 values between 0 and 1, but 256 (28) different combinations (rather permutations) ranging from 00000000 via e.g. 01010101 to 11111111 . Thus, one byte can represent a decimal number between 0(00) and 255.
Each bit can have either value 0 or value 1. A byte is the smallest addressable space in a computer. It consists of 8 bits. Therefore, a byte can represent any one of 256 distinct numbers.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With