将bitarray转换为十六进制字符串 [英] Convert bitarray to hexadecimal string

查看:95
本文介绍了将bitarray转换为十六进制字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个位串联,然后将结果显示为十六进制字符串。有点像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类 [ ^ ]。
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[^].


这篇关于将bitarray转换为十六进制字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆