Home > Blockchain >  how to check single bit in byte using C#
how to check single bit in byte using C#

Time:08-11

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?

CodePudding user response:

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.

CodePudding user response:

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
  • Related