将bitarray转换为十六进制字符串 [英] Convert bitarray to hexadecimal string
问题描述
我想创建一个位串联,然后将结果显示为十六进制字符串。有点像Windows计算器,但我想从脚本生成很多十六进制字符串。我已经完成了代码,但结果不符合我的预期,我无法解释原因:
我尝试了什么:
这是我的代码
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
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)}");
结果是0C-2E。我预计3074.当我在程序员模式下在Microsoft Windows Calculator中写入0011 0000 0111 0100时,HEX值为3074.这对我来说似乎是正确的。
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.
推荐答案
{BitConverter.ToString(byteArray,0)});
结果是0C-2E。我预计3074.当我在程序员模式下在Microsoft Windows Calculator中写入0011 0000 0111 0100时,HEX值为3074.这对我来说似乎是正确的。
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.
BitArray
将这些位存储在一系列int
值中,从最低位开始。
传入false,false,true,true,false,false,false,false
相当于0b0000_1100
,不是0b0011_0000
。
存储在<$中的整数值c $ c> newBitArray 是0b0010_1110_0000_1100
,这是0x2E0C
。
但是因为你一次只抽出一个字节,你就会反过来 -0x0C
,然后是0x2E
。
目前还不完全清楚你想要达到的目标,但是你 BigInteger类 [ ^ ]。
TheBitArray
stores the bits in a series ofint
values, starting with the least significant bit.
Passing infalse, false, true, true, false, false, false, false
is equivalent to0b0000_1100
, not0b0011_0000
.
The integer value you have stored in yournewBitArray
is0b0010_1110_0000_1100
, which is0x2E0C
.
But because you're pulling out a single byte at a time, you're getting them in reverse -0x0C
, followed by0x2E
.
It's not entirely clear what you're trying to achieve, but you might have better luck with the BigInteger class[^].
这篇关于将bitarray转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!