繁体   English   中英

如何使用 C# 检查字节中的单个位

[英]how to check single bit in byte using C#

我想使用 C# 检查接收到的串行通信字节中的单个位是高还是低

我试图写这样的东西:

if(BoxSerialPort.ReadByte() & 0x01)

或者

if(Convert.ToByte(BoxSerialPort.ReadByte()) & 0x01)

编译器发送此错误:

错误 CS0029 无法将类型“int”隐式转换为“bool”

我怎样才能解决这个问题?

使用&运算符

if ((BoxSerialPort.ReadByte() & 0x01) != 0)
...

& - 运算符检查两个 integer 值的每一位并返回一个新的结果值。

假设您的BoxSerialPort43 ,即二进制0010 1011

0x01或简单的1是二进制的0000 0001

&比较每个位,如果相应位在两个操作数中都设置了,则返回1 ,否则返回0

0010 1011

0000 0001

=

0000 0001 (正常整数为1

您的 if 语句现在检查if (1 != 0)这显然是正确的。 0x01位在您的变量中设置。 &运算符通常可以很好地确定是否在 integer 值中设置了某个位。

我会使用compareTo

    using System;

    //byte compare 
    byte num1high = 0x01;
    byte num2low = 0x00;


    if (num1high.CompareTo(num2low) !=0)
        Console.WriteLine("not low");
    if (num1high.CompareTo(num2low) == 0)
        Console.WriteLine("yes is low");

    Console.WriteLine(num1high.CompareTo(num2low));
    Console.WriteLine(num1high.CompareTo(num1high));
    Console.WriteLine(num2low.CompareTo(num1high));

output:

not low
1
0
-1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM