使用bitmask读取C#中的ushort的前2位
我有各种各样的吸管,想迭代数组,并检查该ushort的前两个位是否为11
,如果我想清除它们。但是,我用来阅读条件下的前两个位的位掩码无法正常工作,当前两个位是11
时,IF语句不会触发,
static public void trimData(ushort[] rawData)
{
for(int i = 0; i < rawData.Length; i++)
{
if (((ushort)(rawData[i] & (1 << 15)) == 1) && ((ushort)(rawData[i] & (1 << 14)) == 1))
{
rawData[i] = (ushort)(rawData[i]&~(1<<15));
rawData[i] = (ushort)(rawData[i]&~(1<<14));
}
}
}
我该如何使用bitmasks正确执行此操作。 ?
I have an array of ushorts and want to iterate over the array and check if the first two bits of that ushort are 11
if so I want to clear them. However the bit mask I am using to read the first two bits in my conditional are not working properly and the if statement does not trigger when the first two bits are 11
static public void trimData(ushort[] rawData)
{
for(int i = 0; i < rawData.Length; i++)
{
if (((ushort)(rawData[i] & (1 << 15)) == 1) && ((ushort)(rawData[i] & (1 << 14)) == 1))
{
rawData[i] = (ushort)(rawData[i]&~(1<<15));
rawData[i] = (ushort)(rawData[i]&~(1<<14));
}
}
}
How can I use bitmasks to do this correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将这些位移动以使它们成为最右边的位,然后用0b11掩盖:
要清除这些位,您使用XOR
^
(由于1 ^ 1 == 0
):让我们结合这些部分:
最后,方法可以是
You can shift these bits to have them being the rightmost ones and then mask with 0b11:
To clear these bits you use XOR
^
(since1 ^ 1 == 0
):Let's combine these parts:
Finally, the method can be
你能尝试一下吗?
49152 =(2^14) +(2^15)
Can you try this?
49152 = (2^14) + (2^15)