Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. How do you find value of bits in byte

How do you find value of bits in byte

Scheduled Pinned Locked Moved C#
data-structuresquestion
11 Posts 7 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    gwithey
    wrote on last edited by
    #1

    I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

    M M 0 D L 5 Replies Last reply
    0
    • G gwithey

      I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

      M Offline
      M Offline
      Mirko1980
      wrote on last edited by
      #2

      You can use the BitArray class to check the value of single bits into a byte array.

      G 2 Replies Last reply
      0
      • G gwithey

        I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

        M Offline
        M Offline
        monstale
        wrote on last edited by
        #3

        Hi, shifting is the key. ;-)

        byte b = 0xaa;
        if ((b && 0x01) > 0)
        {
        //bit0 = 1
        }
        else
        {
        //bit0 = 0
        }
        if (((b >> 1) && 0x01) > 0)
        {
        //bit1 = 1
        }
        else
        {
        //bit1 = 0
        }

        etc. bye

        G 1 Reply Last reply
        0
        • G gwithey

          I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

          0 Offline
          0 Offline
          0x3c0
          wrote on last edited by
          #4

          It's a matter of using ANDs, and other boolean stuff (if you want to read multiple bits). Basically, you use the formula: bitNSet = (originalInteger & (1 << N) == 1 << N) Effectively, every integer is represented by a binary sequence. For example, 39 would be represented by 100111. Each one and zero is a bit. To get a bit, you have to AND it, which gets all the bits which are set in both of the numbers given to it. For example, 39 AND 4 would be worked out like so: 100111 AND 000100 = ------ 000100 As you can see, you end up with a binary sequence, which is represented by 4 in decimal (base-10). You use the AND against a bit pattern to see if that bit is set. Now, unfortunately, you don't get a true or false value. Note that the result of 39 AND 4 was 4. So, we can apply this further, and say that if q AND n is equal to n, then bit n was set. Now we just have to get a binary pattern to use against the AND. To get this, we just use the << operator. It will perform a left binary shift on the left operand. So 1 << 5 would result in 100000, 1 << 2 would result in 100, etc. Those numbers are in binary format by the way. So, shifting 1 left by N will give us a binary pattern where only the Nth bit is set. By ANDing that with the original integer, we can check if the bit is set

          Between the idea And the reality Between the motion And the act Falls the Shadow

          1 Reply Last reply
          0
          • M monstale

            Hi, shifting is the key. ;-)

            byte b = 0xaa;
            if ((b && 0x01) > 0)
            {
            //bit0 = 1
            }
            else
            {
            //bit0 = 0
            }
            if (((b >> 1) && 0x01) > 0)
            {
            //bit1 = 1
            }
            else
            {
            //bit1 = 0
            }

            etc. bye

            G Offline
            G Offline
            gwithey
            wrote on last edited by
            #5

            It looks like a good idea i just cant get it to work as i cant compare the byte to 0x01

            M 1 Reply Last reply
            0
            • M Mirko1980

              You can use the BitArray class to check the value of single bits into a byte array.

              G Offline
              G Offline
              gwithey
              wrote on last edited by
              #6

              Thanx for the advice this looks like a useful class. I tried looking through the byte with .length but noticed there was a get() position which is what i was looking for. As somthing like getchar()/ charAt() is perfect.

              1 Reply Last reply
              0
              • M Mirko1980

                You can use the BitArray class to check the value of single bits into a byte array.

                G Offline
                G Offline
                gwithey
                wrote on last edited by
                #7

                I think this is the idea

                BitArray byte1 = new BitArray(commandData.Data[0]);
                enumLEDAndBuzzer lcdAndBuzzState = enumLEDAndBuzzer.NULL;

                              if ((byte1.Get(byte1.Count - 1)) == 0x31) // 1
                              {
                                 lcdAndBuzzState = enumLEDAndBuzzer.BUZZER\_STATE;
                              }
                              else
                              {
                                 lcdAndBuzzState = enumLEDAndBuzzer.NULL;
                              }
                               if((byte1.Get(byte1.Count - 2)) == 0x31) // 1
                              {
                              }
                              else
                              {
                                 lcdAndBuzzState = enumLEDAndBuzzer.NULL;
                              }
                

                From my understanding i should be able to work from right to left by (count - 1++). Thanx again

                1 Reply Last reply
                0
                • G gwithey

                  It looks like a good idea i just cant get it to work as i cant compare the byte to 0x01

                  M Offline
                  M Offline
                  monstale
                  wrote on last edited by
                  #8

                  Hi, yes, I'm sorry. I've made a little fault: not (byte1 **&&** 0x01) > 0 but (byte1 **&** 0x01) > 0 sorry

                  1 Reply Last reply
                  0
                  • G gwithey

                    I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

                    D Offline
                    D Offline
                    DaveyM69
                    wrote on last edited by
                    #9

                    In addition to the excellent advice you've been given - all the Boolean logical operator variants are easy to implement as shown below. Also, using an enum with the Flags attribute can make getting individual bits easier as you can give your enum members more descriptive names.

                    class Program
                    {
                    static void Main(string[] args)
                    {
                    byte baseValue = 0x01;
                    byte otherValue = 0x07;
                    Console.WriteLine("Base Value = {0} : Other Value = {1}", baseValue, otherValue);
                    Console.WriteLine("AND result = {0}", baseValue & otherValue);
                    Console.WriteLine("OR result = {0}", baseValue | otherValue);
                    Console.WriteLine("XOR result = {0}", baseValue ^ otherValue);
                    Console.WriteLine("NOT result (Base only) = {0}", (byte)~baseValue);
                    Console.WriteLine("NAND result = {0}", (byte)~(baseValue & otherValue));
                    Console.WriteLine("NOR result = {0}", (byte)~(baseValue | otherValue));

                        Console.WriteLine("Bit0 of Base Value = {0}", baseValue & (byte)Bits.Bit0);
                        Console.WriteLine("Bit0 and Bit1 of Other Value = {0}", otherValue & (byte)(Bits.Bit0 | Bits.Bit1));
                        Console.ReadKey();
                    }
                    

                    }

                    [Flags]
                    public enum Bits : byte
                    {
                    None = 0,
                    Bit0 = 1,
                    Bit1 = 2,
                    Bit2 = 4,
                    Bit3 = 8,
                    Bit4 = 16,
                    Bit5 = 32,
                    Bit6 = 64,
                    Bit7 = 128
                    }

                    If you want to work with binary values directly, unfortunately there is no binary literal in C#. I made this article[^] quite a while ago to make it easier to work with binary strings, you may find it of some use.

                    Dave
                    BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                    Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                    Why are you using VB6? Do you hate yourself? (Christian Graus)

                    P 1 Reply Last reply
                    0
                    • G gwithey

                      I have looked in all my books and on the net and cant find a way to do this, it just tells me about shifting bits which will not be appropriate. I have a program that recieves a byte[] from an external source. The array elements represent different things eg(byte[0] bit 1 (rightmost)) = buzzer state (1 on: 0 off) In the command i recieve there will be 3 bytes, with each contained bit representing a buzzer or LED and its state on or off; Does anyone know how i can look through the bits and check there state? Thanx George

                      L Offline
                      L Offline
                      Luc Pattyn
                      wrote on last edited by
                      #10

                      Hi, this code works like a bit getter on a byte array:

                      public static bool bitGetter(byte[] bytes, int index) {
                      int byteNumber=index/8;
                      int bitNumber=index%8;
                      int bitMask=1<<bitNumber;
                      int byt=bytes[byteNumber];
                      int bit=byt&bitMask;
                      if (bit==0) return false;
                      return true;
                      }

                      and the condensed version is:

                      public static bool bitGetter(byte[] bytes, int index) {
                      return 0!=bytes[index/8]&(1<<(index%8));
                      }

                      :)

                      Luc Pattyn [Forum Guidelines] [My Articles]


                      The quality and detail of your question reflects on the effectiveness of the help you are likely to get. Show formatted code inside PRE tags, and give clear symptoms when describing a problem.


                      1 Reply Last reply
                      0
                      • D DaveyM69

                        In addition to the excellent advice you've been given - all the Boolean logical operator variants are easy to implement as shown below. Also, using an enum with the Flags attribute can make getting individual bits easier as you can give your enum members more descriptive names.

                        class Program
                        {
                        static void Main(string[] args)
                        {
                        byte baseValue = 0x01;
                        byte otherValue = 0x07;
                        Console.WriteLine("Base Value = {0} : Other Value = {1}", baseValue, otherValue);
                        Console.WriteLine("AND result = {0}", baseValue & otherValue);
                        Console.WriteLine("OR result = {0}", baseValue | otherValue);
                        Console.WriteLine("XOR result = {0}", baseValue ^ otherValue);
                        Console.WriteLine("NOT result (Base only) = {0}", (byte)~baseValue);
                        Console.WriteLine("NAND result = {0}", (byte)~(baseValue & otherValue));
                        Console.WriteLine("NOR result = {0}", (byte)~(baseValue | otherValue));

                            Console.WriteLine("Bit0 of Base Value = {0}", baseValue & (byte)Bits.Bit0);
                            Console.WriteLine("Bit0 and Bit1 of Other Value = {0}", otherValue & (byte)(Bits.Bit0 | Bits.Bit1));
                            Console.ReadKey();
                        }
                        

                        }

                        [Flags]
                        public enum Bits : byte
                        {
                        None = 0,
                        Bit0 = 1,
                        Bit1 = 2,
                        Bit2 = 4,
                        Bit3 = 8,
                        Bit4 = 16,
                        Bit5 = 32,
                        Bit6 = 64,
                        Bit7 = 128
                        }

                        If you want to work with binary values directly, unfortunately there is no binary literal in C#. I made this article[^] quite a while ago to make it easier to work with binary strings, you may find it of some use.

                        Dave
                        BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn)
                        Visual Basic is not used by normal people so we're not covering it here. (Uncyclopedia)
                        Why are you using VB6? Do you hate yourself? (Christian Graus)

                        P Offline
                        P Offline
                        PIEBALDconsult
                        wrote on last edited by
                        #11

                        10! This is what I would suggest.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups