简体   繁体   English

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

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

I want to check if single bit in received serial communication byte is high or low using C#我想使用 C# 检查接收到的串行通信字节中的单个位是高还是低

I was trying to write something like this:我试图写这样的东西:

if(BoxSerialPort.ReadByte() & 0x01)

or或者

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

The compiler sends this error:编译器发送此错误:

Error CS0029 Cannot implicitly convert type 'int' to 'bool'错误 CS0029 无法将类型“int”隐式转换为“bool”

How can I fix this?我怎样才能解决这个问题?

Use the & -operator使用&运算符

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

The & - operator checks every bit of two integer values and returns a new resulting value. & - 运算符检查两个 integer 值的每一位并返回一个新的结果值。

Lets say your BoxSerialPort is 43 which would be 0010 1011 in binary.假设您的BoxSerialPort43 ,即二进制0010 1011

0x01 or simply 1 is 0000 0001 in binary. 0x01或简单的1是二进制的0000 0001

The & compares every bit and returns 1 if the corresponding bit is set in both operands or 0 if not. &比较每个位,如果相应位在两个操作数中都设置了,则返回1 ,否则返回0

0010 1011

0000 0001

= =

0000 0001 (which is 1 as normal integer) 0000 0001 (正常整数为1

Your if-statement now checks if (1 != 0) and this is obviously true.您的 if 语句现在检查if (1 != 0)这显然是正确的。 The 0x01 -bit is set in your variable. 0x01位在您的变量中设置。 The & -operator is generally good to figure out if a bit is set in a integer value or not. &运算符通常可以很好地确定是否在 integer 值中设置了某个位。

I would use compareTo我会使用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: output:

not low
1
0
-1

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

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