读取一个字节的高半字节和低半字节
处理存储在一个字节数据中的两个不同值的正确方法是什么?我有一个字节,其中包含两个半字节,每个半字节包含自己的数据。我想将顶部半字节和底部半字节读入它们自己的变量中。
11110000
= 高 4 位节流阀,读入 $throttle
,并且应该是 0 到 15 之间的值。 00001111
= 低4位刹车,读入$brake
,并且应该是0到15之间的值。
不要忘记,驾驶员可以同时踩油门和刹车,因此您可能会得到类似 11000111
的值。我自己提出了一个针对高 4 位的解决方案,它就像使用 >>
(位右移)运算符将低 4 位推开 4 次一样简单。 $Throttle = $ThrBrk>>> 4
,但由于我无法一次性完成低四位的操作,因此在我的源代码中看起来有点糟糕。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对两者使用 AND 运算符,并将高半字节向右移动四位。
Use
AND
operators for both and shift the top nibble four bits to the right.查看 &运算符,它是按位与。要获取第一个(最低有效位),请执行以下操作:
因此,要获取整个“半字节”:
Check out the & operator, which is a bitwise AND. To get the first (least significant bit), do this:
So, to get the whole "nibble":