Converting a boolean array into a hexadecimal number

只愿长相守 提交于 2020-01-21 08:33:00

问题


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.


回答1:


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



回答2:


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

disclaimer: untested




回答3:


The Binary part can be achieved through this method:

bool[] boolArray = {true, false, true} will give 101:

int BoolArrayToInt(bool[] bArray)
{

    char[] caseChar = new char[bArray.Length];

    for(int i = 0; i < bArray.Length; i++)
    {
        if (bArray[i] == true)
        {
            caseChar[i] = '1';
        }
        else
        {
            caseChar[i] = '0';
        }
    }

    string caseString = new string(caseChar);
    int caseNum = System.Convert.ToInt32(caseString);
    return caseNum;

}


来源:https://stackoverflow.com/questions/5533545/converting-a-boolean-array-into-a-hexadecimal-number

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!