Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to create a concatenation of bits then display the result as a hexadecimal string. A little bit like the Windows Calculator does except I want to generate a lot a hexadecimal string from a script. I already did the code but the result is not what I expected and I cannot explain why:

What I have tried:

Here is my code

C#
BitArray headerBits = new BitArray(new bool[] { false, false, true, true, false, false, false, false }); // 8
BitArray filterBits = new BitArray(new bool[] { false, true, true });  // 11
BitArray PartitionBits = new BitArray(new bool[] { true, false, true });  // 14
BitArray CompanyPrefixBits = new BitArray(new bool[] { false, false }); // 16

BitArray newBitArray = new BitArray(headerBits.Cast<bool>()
	.Concat(filterBits.Cast<bool>())
	.Concat(PartitionBits.Cast<bool>())
	.Concat(CompanyPrefixBits.Cast<bool>())
	.ToArray());
var byteArray = newBitArray.ToByteArray();
Console.WriteLine($"{BitConverter.ToString(byteArray, 0)}");


Result in condole is 0C-2E. I expected 3074. When I write 0011 0000 0111 0100 in Microsoft Windows Calculator in Programmer mode the HEX value is 3074. And this seems correct to me.
Posted
Updated 13-Sep-18 8:25am
Comments
Sinisa Hajnal 13-Sep-18 7:09am    
You need to convert each 4 bits independently. You code works in reverse order, if you check it from right to left, you'll see 2E 0C.

1 solution

The BitArray stores the bits in a series of int values, starting with the least significant bit.

Passing in false, false, true, true, false, false, false, false is equivalent to 0b0000_1100, not 0b0011_0000.

The integer value you have stored in your newBitArray is 0b0010_1110_0000_1100, which is 0x2E0C.

But because you're pulling out a single byte at a time, you're getting them in reverse - 0x0C, followed by 0x2E.

It's not entirely clear what you're trying to achieve, but you might have better luck with the BigInteger class[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900