How to go through every byte bit

I do not know how to implement the following algorithm.

For example, I have int = 26, this is "11010" in binary format. Now I need to implement one operation for 1, another for 0, from left to right, to the end of the byte. But I really don't know how to implement this. Maybe I can convert the binary to a char array, but I don't know how to do this. btw, int is 26 only in the example, in the application it will be random.

+4
source share
6 answers

Since you want to go 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 simply scans every bit in the byte, from the most significant to zero.

+8
source

You can use modulo arithmetic or bitmask to get what you need.

Arithmetic Modules:

 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. 
+4
source

In C, C ++ and similar syntax, you can determine if the right-most bit in integer i 1 or 0, checking if i & 1 non-zero or zero. (Note that single & , meaning bitwise AND, and not && , meaning logical AND). For bits of second-to-right, you check i & 2 ; for the third you check i & 4 etc. degrees of two.

More generally, to determine if a bit is equal, that j th on the right is zero, you can check if i & (1 << (j-1)) != 0 . << indicates a left shift; 1 << (j-1) is essentially equivalent to 2 j-1 .

So for a 32-bit integer, your loop would look something like this:

 unsigned int i = 26; /* Replace this with however it 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 */ } 

Hope this is enough to get you started.

+2
source

I am using this option:

 isBitSet = ((bits & 1) == 1); bits = bits >> 1 

I find the answer also in stackoverflow:

How to scroll and print Int, Long, Float, or BigInteger bits correctly?

+2
source

I'm not quite sure what you say you want to do. You can probably use bitmasks to do any bit manipulation in your byte if that helps.

0
source

Hello Look at the bit, offset and bitwise, and.

0
source

Source: https://habr.com/ru/post/1332409/


All Articles