Answer the question
In order to leave comments, you need to log in
How to check all bits in a byte?
You need to check all the bits in a byte. The only thing that comes to mind is to check each bit individually:
/*Грубо вырезанный кусок кода*/
...
byte err;
...
if ((err & 0x01) != 0) AddMessage("1", "А1");
if ((err & 0x02) != 0) AddMessage("1", "А2");
if ((err & 0x04) != 0) AddMessage("2", "Б1");
if ((err & 0x08) != 0) AddMessage("2", "Б2");
if ((err & 0x10) != 0) AddMessage("1", "АА1");
if ((err & 0x20) != 0) AddMessage("1", "АА2");
if ((err & 0x40) != 0) AddMessage("2", "ББ1");
if ((err & 0x80) != 0) AddMessage("2", "ББ2");
...
Answer the question
In order to leave comments, you need to log in
Such if constructs should be replaced with a dictionary.
If your indexes are sequential and start from zero, then a list or an array can play the role of a dictionary.
Either way, you need to map "bit number" => "message".
I propose to save the bit number, so that it would be more convenient to write down the table and go through it in a cycle. The shift operator will give you the constant you need for the AND operation.
Total:
using System;
using System.Collections.Generic;
public class Test
{
private static void AddMessage(Tuple<string, string> message)
{
Console.WriteLine("{0}, {1}", message.Item1, message.Item2);
}
public static void Main()
{
byte val = 176;
for (int i = 0; i <= 7; i++)
{
if ((val & (1 << i)) != 0)
AddMessage(messageByBitIndex[i]);
}
}
private static Tuple<string, string>[] messageByBitIndex =
{
Tuple.Create("1", "А1"), // 0
Tuple.Create("1", "А2"), // 1
Tuple.Create("2", "Б1"), // 2
Tuple.Create("2", "Б2"), // 3
Tuple.Create("1", "АА1"), // 4
Tuple.Create("1", "АА2"), // 5
Tuple.Create("2", "ББ1"), // 6
Tuple.Create("2", "ББ2"), // 7
};
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question