gpt4 book ai didi

c# - BitArray(16) 到 HexString

转载 作者:行者123 更新时间:2023-11-30 17:37:27 24 4
gpt4 key购买 nike

我正在尝试将 BitArray 转换为十六进制字符串

我的测试 BitArray 是“0000001010000000”,它应该以十六进制返回“02 80”

尝试了以下方法:

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

然后,通过检查我创建的 BitArray 对象并获取对应于该二进制字符串的 640 十进制值。

但我找不到将其转换为十六进制的方法。

我避免使用不同类的字节数组。

这行得通,但有点复杂,我相信一定有更简单的方法,但我不明白为什么我必须切换值。

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

有什么建议吗?

最佳答案

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

所以您只想创建十六进制值的字符串表示形式?这可以很容易地完成:

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

甚至 string s = $"{dec:X}";

对于前导零(如您在问题中所示)最好是

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

请注意,十六进制的 640280 而不是您在问题中所述的 208


获取 BitArray 的“值”的一种简单方法是(长度 <= 32):

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

关于c# - BitArray(16) 到 HexString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38056854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com