I have BitArray
with differents size and i want to get the conversion in a hex string.
I have tried to convert the BitArray
to byte[]
, but it didn't give me the right format. (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)
Thanks
I have implemented three useful Extension methods for BitArray which is capable of doing what you want:
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With