Manjunath ST
Manjunath ST

Reputation: 119

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)

Upvotes: 0

Views: 179

Answers (2)

Vivek Nuna
Vivek Nuna

Reputation: 1

You can just use ToString() method.

byte[] arr= new byte[8];
int index = 0; 
string hexValue = arr[index].ToString("X");

Upvotes: 1

Matthew Watson
Matthew Watson

Reputation: 109567

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

Upvotes: 1

Related Questions