以字节为单位读取顶部半字节和底部半字节 [英] Reading top nibble and bottom nibble in a byte

查看:138
本文介绍了以字节为单位读取顶部半字节和底部半字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

处理存储在一个字节数据中的两个不同值的正确方法是什么?我有一个字节,其中包含两个半字节,每个半字节均包含自己的数据。我想将前半字节和后半字节读入它们自己的变量。

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 =高4位油门,将其读入 $ throttle ,并且其值应为0到15。
00001111 =低4位制动器,应读入 $ brake ,其值应为0到15。

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.

别忘了,驾驶员可以同时应用油门和制动器,因此您可能会得到类似 11000111 的值。我自己想出了一个高4位的解决方案,就像用> (bit右移)运算符4次。 $ Throttle = $ ThrBrk>> 4 ,但是由于我不能一口气把低四位做到这一点,所以我的源代码看起来有点不好。

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.

推荐答案

同时使用运算符,并将顶部半字节右移四位。

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

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

这篇关于以字节为单位读取顶部半字节和底部半字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆