Search code examples
c#bytebittostringbitarray

How do i create byte array that contains 64 bits array and how do i convert those bits into hex value?


I want to create byte array that contains 64 bits, How can i get particular bits values say 17th bit, and also how can i get hex value of that index of byte? I did like this, Is this correct?

byte[] _byte = new byte[8];
var bit17=((((_byte[2]>>1)& 0x01);
string hex=BitConverter.ToString(_byte,2,4).Replace("-", string.Empty)

Solution

  • You could use a BitArray:

    var bits = new BitArray(64);
    
    bool bit17 = bits[17];
    

    I'm not sure what you mean by the "hex value of that bit" - it will be 0 or 1, because it's a bit.

    If you have the index of a bit in a byte (between 0 and 7 inclusive) then you can convert that to a hex string as follows:

    int bitNumber = 7; // For example.
    byte value = (byte)(1 << bitNumber);
    string hex = value.ToString("x");
    Console.WriteLine(hex);