如何检查字节的最后一位 [英] how to check last bit of byte is one
本文介绍了如何检查字节的最后一位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有:
byte[] buffer;
if((buffer[6])&(0x01))
{
}
我想检查第6个字节中的最后一位是否应该为1,因此我正在应用此操作,但它引发了我错误:无法将类型"int"隐式转换为"bool".
I want to check the last bit in the 6th byte should be one so I am applying this but it throws me error: Cannot implicitly convert type ''int'' to ''bool''.
推荐答案
无法将类型"int"隐式转换为"bool".
看起来您在IF
语句中的表达式没有被评估为布尔值.可能是错误的&"运算符?
Cannot implicitly convert type ''int'' to ''bool''.
Looks like your expression in theIF
statement is not evaluating as a boolean value. Probably a wrong ''&'' operator?
byte[] buffer;
byte one = 1 ;
if((buffer[6])== one)
或:
使用 MSDN:Byte.CompareTo方法(字节)
[^ ]
Or:
Use MSDN: Byte.CompareTo Method (Byte)
[^]
if(one.CompareTo(buffer[6]))
{
}
你好,
试试这个:
hello,
Try this:
byte[] teste = new byte[3];
teste[0] = 0x01;
teste[1] = 0x02;
teste[2] = 0x03;
if (teste[2].Equals(0x03))
{
}
else
{
}
问题是您的if语句正在使用按位AND运算符计算数值. C#不会将整数零/非零隐式转换为布尔值false/true.
只需将AND的结果与零进行比较:
The problem is that your if statement is computing a numeric value with the bit-wise AND operator. c# does not implicitly convert integer zero/non-zero to boolean false/true.
Just compare the result of the AND against zero:
if((buffer[6] & 0x01) != 0)
{
// low-order bit is set
}
如果需要同时检查多个位,请与位掩码进行比较:
If you needed to check for multiple bits at the same time, compare against the bitmask:
if((buffer[6] & 0x81) == 0x81)
{
// both highest-order and low-order bits (binary: 10000001) are set
}
这篇关于如何检查字节的最后一位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文