[英]C# - BitArray to Hex
I have BitArray
with differents size and i want to get the conversion in a hex string. 我有不同大小的
BitArray
,我想以十六进制字符串形式进行转换。
I have tried to convert the BitArray
to byte[]
, but it didn't give me the right format. 我试图将
BitArray
转换为byte[]
,但是它没有给我正确的格式。 ( Converting a boolean array into a hexadecimal number ) ( 将布尔数组转换为十六进制数 )
For exemple, a BitArray
of 12, and i want the string to be A8C (3 hexa because 12 bits) 例如,一个
BitArray
为12,我希望该字符串为A8C(3个六进制,因为12位)
Thanks 谢谢
I have implemented three useful Extension methods for BitArray which is capable of doing what you want: 我为BitArray实现了三个有用的扩展方法 ,这些方法可以执行您想要的操作:
public static byte[] ConvertToByteArray(this BitArray bitArray)
{
byte[] bytes = new byte[(int)Math.Ceiling(bitArray.Count / 8.0)];
bitArray.CopyTo(bytes, 0);
return bytes;
}
public static int ConvertToInt32(this BitArray bitArray)
{
var bytes = bitArray.ConvertToByteArray();
int result = 0;
foreach (var item in bytes)
{
result += item;
}
return result;
}
public static string ConvertToHexadecimal(this BitArray bitArray)
{
return bitArray.ConvertToInt32().ToString("X");
}
You can try direct 您可以尝试直接
StringBuilder sb = new StringBuilder(bits.Length / 4);
for (int i = 0; i < bits.Length; i += 4) {
int v = (bits[i] ? 8 : 0) |
(bits[i + 1] ? 4 : 0) |
(bits[i + 2] ? 2 : 0) |
(bits[i + 3] ? 1 : 0);
sb.Append(v.ToString("x1")); // Or "X1"
}
String result = sb.ToString();
Solution provide at Converting a boolean array into a hexadecimal number is correct. 提供的解决方案将布尔数组转换为十六进制是正确的。
BitArray arr = new BitArray(new int[] { 12 });
byte[] data1 = new byte[100];
arr.CopyTo(data1, 0);
string hex = BitConverter.ToString(data1);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.