将位插入字节
我正在看一个从字节读取位的示例,其实现看起来简单且易于理解。我想知道是否有人有类似的示例来说明如何将位插入字节或字节数组,这更容易理解并且也像下面的示例一样实现。
这是我发现的阅读示例字节中的位:
static int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}
这就是我想要做的。这是我当前的实现,我只是对位掩码/移位等有点困惑,所以我试图找出是否有更简单的方法来完成我正在做的事情
BYTE Msg[2];
Msg_Id = 3;
Msg_Event = 1;
Msg_Ready = 2;
Msg[0] = ( ( Msg_Event << 4 ) & 0xF0 ) | ( Msg_Id & 0x0F ) ;
Msg[1] = Msg_Ready & 0x0F; //MsgReady & Unused
I was looking at an example of reading bits from a byte and the implementation looked simple and easy to understand. I was wondering if anyone has a similar example of how to insert bits into a byte or byte array, that is easier to understand and also implement like the example below.
Here is the example I found of reading bits from a byte:
static int GetBits3(byte b, int offset, int count)
{
return (b >> offset) & ((1 << count) - 1);
}
Here is what I'm trying to do. This is my current implementation, I'm just a little confused with the bit-masking/shifting, etc., so I'm trying to find out if there is an easier way to do what I'm doing
BYTE Msg[2];
Msg_Id = 3;
Msg_Event = 1;
Msg_Ready = 2;
Msg[0] = ( ( Msg_Event << 4 ) & 0xF0 ) | ( Msg_Id & 0x0F ) ;
Msg[1] = Msg_Ready & 0x0F; //MsgReady & Unused
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您使用连续的整数常量值(如上例所示),则在将这些常量放入字节中时,应使用这些常量移动位。否则它们会重叠:在您的示例中,
Msg_Id
等于Msg_Event &消息_就绪
。这些可以像这样使用(请注意,字节内的位从 0 开始索引。)另一种方法是使用 2 的幂作为常量值:
请注意,在上面的代码中,使用
0x0F
或 < code>0xF0 并不是真正需要的:(Msg_Id & 0x0F) == Msg_Id
和((Msg_Event << 4) & 0xF0) == (Msg_Event < ;<4)
。If you are using consecutive integer constant values like in the example above, you should shift the bits with these constants when putting them inside a byte. Otherwise they overlap: in your example,
Msg_Id
equalsMsg_Event & Msg_Ready
. These can be used like(Note that bits within a byte are indexed from 0.) The other approach would be using powers of 2 as constant values:
Note that in your code above, masking with
0x0F
or0xF0
is not really needed:(Msg_Id & 0x0F) == Msg_Id
and((Msg_Event << 4) & 0xF0) == (Msg_Event << 4)
.您可以使用位字段。例如:
然后您可以使用联合来操作位域或字节,如下所示:
You could use a bit field. For instance :
You could then use a union to manipulate either the bitfield or the byte, something like this :