V
V
Vladislav2015-09-20 23:36:07
C++ / C#
Vladislav, 2015-09-20 23:36:07

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");
...

I don't think this is the best solution. It may be necessary to check 2 bytes in this way ...
Tell me, please, what and how can I replace the if constructs?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Stanislav Makarov, 2015-09-21
@int_22h

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
  };
}

ideone.com/vbLapl

T
Tsiren Naimanov, 2015-09-20
@ImmortalCAT

cycle?
googol

S
Saboteur, 2015-09-21
@saboteur_kiev

I'm not strong in C#, because the syntax is wrong, but the idea is this:
#define CHECK_BIT(var,pos) ((var) & (1<<(pos)))
for (int bit = 1; bit <= 8; bit++)
{
if (CHECK_BIT(err, bit))
{
string = string + mystringarray[bit];
}
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question