简体   繁体   中英

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#

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'

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.

Lets say your BoxSerialPort is 43 which would be 0010 1011 in binary.

0x01 or simply 1 is 0000 0001 in binary.

The & compares every bit and returns 1 if the corresponding bit is set in both operands or 0 if not.

0010 1011

0000 0001

=

0000 0001 (which is 1 as normal integer)

Your if-statement now checks if (1 != 0) and this is obviously true. The 0x01 -bit is set in your variable. The & -operator is generally good to figure out if a bit is set in a integer value or not.

I would use 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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