Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a boolean array into a hexadecimal number

Is there an easy way to convert an array of boolean values into 8-bit hexadecimal equivlents? For example, if I have

 bool[] BoolArray = new bool[] { true,false,true,true,false,false,false,true };

If true values=1 and false values=0 then I'd like a method or function that would convert the above array to 0xB1 (10110001).

Does there exist such a function or method to do this? I am using C#, by the way.

like image 409
Icemanind Avatar asked Dec 21 '22 15:12

Icemanind


2 Answers

Yes, you can use the BitArray class. Something like this should do it:

BitArray arr = new BitArray(BoolArray);
byte[] data = new byte[1];
arr.CopyTo(data, 0);

If by "8-bit hexadecimal" you mean the string representation, you can use the BitConverter class for that:

string hex = BitConverter.ToString(data);
like image 65
Guffa Avatar answered Jan 16 '23 11:01

Guffa


How about

static int BoolArrayToInt(bool[] arr)
{
    if (arr.Length > 31)
        throw new ApplicationException("too many elements to be converted to a single int");
    int val = 0;
    for (int i = 0; i < arr.Length; ++i)
        if (arr[i]) val |= 1 << i;
    return val;
}

static string ToHexStr(int i) { return i.ToString("X8"); }

note: an editor remarked that arr[0] is the LSB but he expected MSB. This is an API consideration, if you prefer your LSB to be at arr[length-1] just reverse the array before passing to that function.

like image 20
v.oddou Avatar answered Jan 16 '23 11:01

v.oddou