1

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, but as I can't do that in one move for the lower four bits it looks kinda bad in my source code.

Dan D.
  • 73,243
  • 15
  • 104
  • 123
Mark Tomlin
  • 8,593
  • 11
  • 57
  • 72

2 Answers2

6

Use ANDoperators for both and shift the top nibble four bits to the right.

$brake = $value & 0x0F;
$throttle = ($value & 0xF0) >> 4;
Kaivosukeltaja
  • 15,541
  • 4
  • 40
  • 70
2

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;
Emil Vikström
  • 90,431
  • 16
  • 141
  • 175