Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - BitArray to Hex

Tags:

c#

.net

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

like image 579
D. MIZRAHI Avatar asked Oct 12 '25 11:10

D. MIZRAHI


2 Answers

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");
    }
like image 102
Amir Mahdi Nassiri Avatar answered Oct 15 '25 00:10

Amir Mahdi Nassiri


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();
like image 33
Dmitry Bychenko Avatar answered Oct 14 '25 23:10

Dmitry Bychenko