4

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

Community
  • 1
  • 1
D. MIZRAHI
  • 45
  • 1
  • 7

3 Answers3

4

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");
    }
Amir Mahdi Nassiri
  • 1,190
  • 13
  • 21
2

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();
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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);
Community
  • 1
  • 1
M.S.
  • 4,283
  • 1
  • 19
  • 42