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

4
  • stackoverflow.com/a/4619295/4928207 Commented May 11, 2016 at 12:31
  • 1
    And what if BitArray has a size of 13? Commented May 11, 2016 at 12:36
  • Coudn't you just trim your result string to the length of Math.Ceil(BitArray.Length / 4.0)? Commented May 11, 2016 at 12:44
  • @DmitryBychenko BitArray are a multiple of 4 Commented May 11, 2016 at 12:57

3 Answers 3

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");
    }
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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);

2 Comments

This solution is working for BitArray which are multiple of 8. But for 12 it doesn't work
solved like this: var data1 = new byte[(arr.Length - 1) / 8 + 1];

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.