MarkT
Thank you very much for that clear and short example.
Just to make sure I understand how this works, if I wanted to split the information up so that it is split like this [00000000] where the
- first split shown as the blue bits consist of a number 0-15
- the second split shown as the green bits consist of a number 0-7
- the third split shown as the red bit consist of a boolean.
The I would I write it this way?
byte byte1 = ((num1 & 15) << 5) | ((num2 & 7) << 2) | (bool1 ? 0x02 : 0x00);
and separate it this way?
byte num1 = (byte1 >> 5) & 15 ;
byte num2 = (byte1 >> 2) & 7 ;
boolean bool1 = (byte1 & 0x02) != 0 ;
econjack
I remember how the operators work from reading a programming book a while back, I haven't quite figured out what the bitwise AND operator has to do with the code. I think you are explaining what the & symbol in (byte1 >> 2) & 7 ; does so that it knows the rest of the bits except the ones that are in the byte of interest are looked at. And that is why you list the highest possible number of the bits that are looked at so it knows that all the 1 bits in that section are to be looked at?
It would have been a little clearer if you had demonstrated the example to look at a number in the range of 1 to 7 rather than a boolean, but I think I understand the concept. Correct me if I have something mixed up below.
You want to perform what's called bit masking using the bitwise operators. For example, suppose the base number is 165. Its bit pattern is:
10100101
Using the bitwise AND operator:
byte mask = 240;
byte blueInt = base & 0x11110000;
which becomes:
10100101 // base
& 11110000 // mask
10100000 // blueInt
and because we tell it to go over 5 with byte num1 = (byte1 >> 5) & 15 ; it knows to ignore the 5 0's so instead of being 101000000 which is 240, it knows that it is just 1010 which is Ten.
If you want the green int:
byte GreenInt = base & 0x0000110;
10100101 // base
& 00001110 // mask = 2
00000100 // greenInt
and because we told it go over 2 in this code
byte num2 = (byte1 >> 2) & 7 ;
it knows to ignore the first 0 so instead of being 00000100 which is four it knows it is just 0000010 which is two.
This would have been a good example to add to the examples that come pre-loaded when you download the compiler, it not only teaches binary but explains some really interesting things that aren't explained in any of the examples you can easily find.
There is a chance that I misunderstood something in the logic, if so please point it out.