D. MIZRAHI
D. MIZRAHI

Reputation: 45

C# - BitArray to Hex

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

Upvotes: 4

Views: 4749

Answers (3)

Amir Mahdi Nassiri
Amir Mahdi Nassiri

Reputation: 1330

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

Upvotes: 4

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

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

Upvotes: 2

M.S.
M.S.

Reputation: 4423

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

Upvotes: 0

Related Questions