Reading top nibble and bottom nibble in a byte

走远了吗. 提交于 2020-07-30 11:54:09

问题


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.


回答1:


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

$brake = $value & 0x0F;
$throttle = ($value & 0xF0) >> 4;



回答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;


来源:https://stackoverflow.com/questions/5909911/reading-top-nibble-and-bottom-nibble-in-a-byte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!