BitArray(16) to HexString

I'm trying to convert a BitArray to a Hex String

My test BitArray is "0000001010000000" and it should return "02 80" in Hex

Tried the following:

BitArray b = new BitArray(16);
b.Set(7, true);
b.Set(9, true);

Then, by examining the BitArray object I created and do get the 640 decimal value that corresponds to that binary string.

But I can't find the way to convert that to Hex.

I'm avoiding working with Byte Array which is a different class.

This works, but it's kind of complicated I'm sure there must be an easier way and I can't understand why I must switch the values.

byte[] bytes = new byte[2];
b.CopyTo(bytes, 0);
string Retorno = BitConverter.ToString(bytes);
string[] auxstr = Retorno.Split('-');
Retorno = auxstr[1] + "-" + auxstr[0];

Any advice?

Upvotes: 3

Views: 1213

Answers (3)

Nikola.Lukovic
Nikola.Lukovic

Reputation: 1325

Your bitArray sets and string representation are not the same.

You wrote 0000001010000000 which is actually set like this:

BitArray b = new BitArray(16);
b.Set(6, true);
b.Set(8, true);

But your code:

BitArray b = new BitArray(16);
b.Set(7, true);
b.Set(9, true);

actually produces this set of numbers:

0000000101000000

If you want to reproduce Hex 0280 than you should do this:

BitArray b = new BitArray(16);
b.Set(6, true);
b.Set(8, true);

var @string = String.Concat(b.Cast<bool>().Select(x=> { return x ? '1' : '0'; }));
var result = Convert.ToInt32(@string, 2).ToString("X4");

where result will have this value 0280

Upvotes: 0

Ren&#233; Vogt
Ren&#233; Vogt

Reputation: 43876

Then, by examining the BitArray object i created and do get the 640 decimal value that corresponds to that binary string.

So you only want to create a string representation of the hexadecimal value? This can be easily done like that:

int dec = 640;
string s = Convert.ToString(dec, 16);

or even string s = $"{dec:X}";

For leading zeros (as you show in your question) the best would be

string s = $"{dec:X4}";

Note that 640 as hexadecimal is 280 not 208 as you stated in your question.


An easy way to get the "value" of your BitArray is (for length <= 32):

int v = array.OfType<bool>().Select((b, i) => b ? 1 << i : 0).Sum()

Upvotes: 1

sowjanya attaluri
sowjanya attaluri

Reputation: 911

Try this,

string binary = "0000001010000000";

StringBuilder hexvalue= new StringBuilder(binary.Length / 8 + 1);           

int Len = binary.Length % 8;
if (Len != 0)
{               
     binary = binary.PadLeft(((binary.Length / 8) + 1) * 8, '0');
}

for (int i = 0; i < binary.Length; i += 8)
{
     string Bits = binary.Substring(i, 8);
     hexvalue.AppendFormat("{0:X2}", Convert.ToByte(Bits , 2));
}

binary =  hexvalue.ToString();          

Upvotes: 0

Related Questions