gheo
gheo

Reputation: 1

How to check if a particular bit in a buffer is set in C#

I have a c# code which write a hex code to a port for a device. The device reply for the port, I read his answer, I transformed it to a hex and disply it in a text box. So, now I must to check each bits from the answer and display a message in a text box or somthing like that.

Can anybody help me please?

Thank you in advance.

Upvotes: 0

Views: 500

Answers (4)

Sasha
Sasha

Reputation: 8860

Ferdinand already described the way you can check individual bits. Maybe it wasnt clear enough though.

So to check every bit in every byte you should white the code like this:

StringBuilder message = new StringBuilder();
for (int byteNum = 0; byteNum < bytes.Length; byteNum++)
{
  var responseByte = bytes[byteNum];
  for (int bitPos = 0; bitPos < 8; bitPos++)
  {
    message.AppendFormat("Byte {0} bit {1} value is {2}", byteNum, bitPos, (responseByte & (1<<bitPos)) != 0);
  }
}

Hope now it's more clear. The only thing you night want to change is byte and bit order. I don't know for sure how bit sequence is converted to byte array: the 0th bit really might have came the last in the byte.

Upvotes: 0

gheo
gheo

Reputation: 1

namespace read_display_data

{ public partial class Form1 : Form {

    SerialPort port = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);


    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {

        port.Open();
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);

    }

    private void Sendbutton_Click(object sender, EventArgs e)
    {


        port.Write(new byte[] { 0x55, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x5D }, 0, 8)
        byte[] buffer1 = new byte[] { 0x55, 0x08, 0x00, 0x00, 0x00, 0x00, 0x03, 0x5D };

        Log1(LogMsgType.Outgoing, DateTime.Now + "  --  " + ByteArrayToHexString(buffer1) + "\n");

    }


    public enum LogMsgType { Incoming, Outgoing, Normal };

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {

        int bytes = port.BytesToRead;

        byte[] buffer = new byte[bytes];

        port.Read(buffer, 0, bytes);

        Thread.Sleep(100);

        Log(LogMsgType.Incoming, DateTime.Now + "  --  " + ByteArrayToHexString(buffer) + "\n");
        Log2(LogMsgType.Incoming, DateTime.Now + "  --  " + GetInBinaryString(buffer) + "\n");


    }


    private string ByteArrayToHexString(byte[] buffer)
    {
        StringBuilder sb = new StringBuilder(buffer.Length * 3);
        foreach (byte b in buffer)
            sb.Append(Convert.ToString(b, 16).PadLeft(2, '0').PadRight(3, ' '));
        return sb.ToString().ToUpper();


    }


    private string GetInBinaryString(byte[] buffer)
    {

        StringBuilder sb = new StringBuilder(buffer.Length * 8);
        foreach (byte b in buffer)
            sb.Append(Convert.ToString(b, 2).PadLeft(8, '0').PadRight(5, ' '));
        return sb.ToString().ToUpper();




    }

    private void Log(LogMsgType msgtype, string msg)
    {
        textBox1.Invoke(new EventHandler(delegate
        {
            textBox1.SelectedText = string.Empty;
            textBox1.AppendText(msg);
            textBox1.ScrollToCaret();

        }
        ));


    }
    private void Log1(LogMsgType msgtype, string msg)
    {
        textBox2.Invoke(new EventHandler(delegate
        {
            textBox2.SelectedText = string.Empty;
            textBox2.AppendText(msg);
            textBox2.ScrollToCaret();

        }
        ));


    }


    private void Log2(LogMsgType msgtype, string msg)
    {
        textBox3.Invoke(new EventHandler(delegate
        {
            textBox3.SelectedText = string.Empty;
            textBox3.AppendText(msg);
            textBox3.ScrollToCaret();

        }
        ));


    }

Upvotes: 0

Bitwise AND your response with the bit you want to check:

Byte response = (Byte)0xFF;
Boolean isBitOneSet = (response & 0x1) > 0;
Boolean isBitTwoSet = (response & 0x2) > 0;
Boolean isBitThreeSet = (response & 0x4) > 0;

Or use right-shift:

Boolean isBitFiveSet = ((response >> 4) & 0x1) > 0;

if(isBitFiveSet) System.Windows.MessageBox.Show("Five is set");

Upvotes: 2

Sasha
Sasha

Reputation: 8860

You can use Convert.ToString() method if you need binary representation of a number - it is much simpler and efficient than checking every single bit separately. This method can convert to binary and HEX format - whatever you like.

Upvotes: 1

Related Questions