Reading top nibble and bottom nibble in a byte
What's the correct way to handle two distinct values being stored in one byte of data. I have a byte that contains two nibbles each containing their own data. I want to read the top nibble and the bottom nibble into their own variables.
11110000
= High 4 bits throttle, to be read into $throttle
, and should be a value from 0 to 15.
00001111
= Low 4 bits brake, to be read into $brake
, and should be a value from 0 to 15.
Don't forget, drivers can apply the throttle and the brake at the same time, so you might get a value like 11000111
. I've myself come up with a solution for the high 4 bits, and it's as simple as pushing the lower 4 bits out of the way with the >>
(bit shift right) operator 4 times. $Throttle = $ThrBrk >> 4
, b开发者_Go百科ut as I can't do that in one move for the lower four bits it looks kinda bad in my source code.
Use AND
operators for both and shift the top nibble four bits to the right.
$brake = $value & 0x0F;
$throttle = ($value & 0xF0) >> 4;
Check out the & operator, which is a bitwise AND. To get the first (least significant bit), do this:
$lsb = $bits & 1;
So, to get the whole "nibble":
$break = $bits & 15;
精彩评论