Manjunath ST
Manjunath ST

Reputation: 119

How to get bit values from Byte?

I have a byte say 1 byte of elements of 8.. How do i get the bit each values? for example, I want 16th bit value, 17th bit, 18th bit so on..

    byte[] _byte = new byte[8];

Upvotes: 3

Views: 17729

Answers (5)

user160357
user160357

Reputation: 1526

Simple method to it.

Example use:

A :10101010

B :1

Get the 4th bit from A, so you get B

getBit(A, 4);

//gets n'th bit from a byte, returns as an int
int getBit(byte b, int bitNumber) {
   return ((b >> bitNumber) & 0x01);
}

Upvotes: 0

Vivek Nuna
Vivek Nuna

Reputation: 1

public static Boolean GetBitX(byte[] bytes, int x) {
    var index = x/8;
    System.Collections.BitArray ba = new BitArray(new byte[]{bytes[index]});
    return ba.Get(x);
} 

You can use BitArray

Upvotes: 1

Danny
Danny

Reputation: 541

If you want the Xth bit in your Byte Array (I think that is what your asking at least), you need to index the correct Byte from the array and then extract the bit

public static Boolean GetBitX(byte[] bytes, int x) {
    var index = x/8;
    var bit = x-index*8;

    return (bytes[index] & (1<<bit)) != 0;
}

Upvotes: 1

Adil
Adil

Reputation: 148180

You can use BitArray() constructor BitArray((Byte[]) to get bits array from byte array. Use indexer on the bit array to get the required bit.

var bits = new BitArray(_byte);

Now bit 16 would be bits[15];

You can follow this example to understand how you can get the require bit.

byte[] _byte = new byte[3] {1,3,7};
var bits = new BitArray(_byte);
    for(int i=0; i < bits.Length; i++)
        Console.WriteLine(bits[i]);

Output:

True present 1 at bit and false present 0 at bit

First Byte Value = 1 = 00000001 (Binary)

True   = 1            0 bit index 
False  = 0            1 bit index   
False  = 0            2 bit index
False  = 0            3 bit index
False  = 0            4 bit index   
False  = 0            5 bit index
False  = 0            6 bit index
False  = 0            7 bit index  

Second Byte Value = 3 = 00000011 (Binary)

True   = 1            8 bit index 
True   = 1            9 bit index   
False  = 0            10 bit index
False  = 0            11 bit index
False  = 0            12 bit index   
False  = 0            13 bit index
False  = 0            14 bit index
False  = 0            15 bit index  

Third Byte Value = 7 = 00000111 (Binary)

True   = 1            16 bit index 
True   = 1            17 bit index   
True   = 1            18 bit index
False  = 0            19 bit index
False  = 0            20 bit index   
False  = 0            21 bit index
False  = 0            22 bit index
False  = 0            23 bit index  

Upvotes: 6

yeah-buddy
yeah-buddy

Reputation: 424

If you are wanting to work with bits you can use the BitArray class. One of its constructor overloads lets you pass in a byte array. Also to note, the bit will be represented by a boolean with true repesenting '1' and false '0'.

Upvotes: 1

Related Questions