简体   繁体   English

函数将十六进制字符串转换为BitArray C#

[英]Function convert Hex String to BitArray C#

I created the following function which will do as requested (convert HEX string to BitArray). 我创建了以下函数,该函数将按要求执行(将HEX字符串转换为BitArray)。 I am not sure about the efficiency of the function, but my main problem now is that the Convert.ToInt64 function is endian specific . 我不确定函数的效率,但是我现在的主要问题是Convert.ToInt64函数是字节序特定的 When this is ported over to alternate chipsets we will get different results (or exceptions). 将其移植到备用芯片组时,我们将获得不同的结果(或例外)。 So can anyone think of an alternate way to do this conversion??? 因此,谁能想到另一种进行此转换的方式???

public BitArray convertHexToBitArray(string hexData)
    {
        string binary_values = "";
        BitArray binary_array;

            if (hexData.Length <= "FFFFFFFFFFFFFFFF".Length) // Max Int64
            {
                binary_values = Convert.ToString(Convert.ToInt64(hexData, 16), 2);
                binary_array = new BitArray(binary_values.Length);

                for (int i = 0; i < binary_array.Length; i++)
                {
                    if (binary_values[i] == '0')
                    {
                        binary_array[i] = false;
                    }
                    else
                    {
                        binary_array[i] = true;
                    }
                }
            }
   }

I removed most of the error / exception handling to keep this to size so plz forgive that. 我删除了大多数错误/异常处理,以保持此大小,因此请原谅。

here is a simple answer, should work with a string of any length: 这是一个简单的答案,应该使用任意长度的字符串:

public static BitArray ConvertHexToBitArray(string hexData)
{
    if (hexData == null)
        return null; // or do something else, throw, ...

    BitArray ba = new BitArray(4 * hexData.Length);
    for (int i = 0; i < hexData.Length; i++)
    {
        byte b = byte.Parse(hexData[i].ToString(), NumberStyles.HexNumber);
        for (int j = 0; j < 4; j++)
        {
            ba.Set(i * 4 + j, (b & (1 << (3 - j))) != 0);
        }
    }
    return ba;
}

Try this: 尝试这个:

var int64 = Int64.Parse(hexData, NumberStyles.HexNumber);
var bytes = BitConverter.GetBytes(int64);
var bitArray = new BitArray(bytes);

I haven't tested this (consider it pseduo code), but it would be fast: 我还没有测试(考虑一下pseduo代码),但是速度很快:

    public static BitArray ConvertHexToBitArray(string hex)
    {
        Guard.AssertNotNullOrEmpty(hex, "hex");
        Guard.AssertHex(hex, "hex");

        var bits = new BitArray(hex.Length * 4);

        int pos = 0;

        foreach(char c in hex)
        {
            foreach(bool flag in LookupBits(c))
            {
                bits.Set(pos, flag);
                pos++;
            }
        }

        return bits;
    }

    private static readonly Dictionary<char, List<bool>> _hexVsBits = CreateHexLookupTable();

    private static Dictionary<char, List<bool>> CreateHexLookupTable()
    {
        var hexVsBits = new Dictionary<char, List<bool>>();

        hexVsBits.Add('0', CreateBitsArray(false, false, false, false));
        hexVsBits.Add('1', CreateBitsArray(false, false, false, true));
        hexVsBits.Add('2', CreateBitsArray(false, false, true, false));
        hexVsBits.Add('3', CreateBitsArray(false, false, true, true));
        hexVsBits.Add('4', CreateBitsArray(false, true, false, false));
        hexVsBits.Add('5', CreateBitsArray(false, true, false, true));
        hexVsBits.Add('6', CreateBitsArray(false, true, true, false));
        hexVsBits.Add('7', CreateBitsArray(false, true, true, true));

        // complete hex table

        return hexVsBits;
    }

    private static List<bool> CreateBitsArray(bool msb, bool msbMinusOne, bool lsbPlusOne, bool lsb)
    {
        var bits = new List<bool>(4);

        bits.Add(msb);
        bits.Add(msbMinusOne);
        bits.Add(lsbPlusOne);
        bits.Add(lsb);

        return bits;
    }

    private static IEnumerable<bool> LookupBits(char hexValue)
    {
        return _hexVsBits[hexValue];
    }
}

And the guards: 和卫兵:

public static class Guard
{
    public static void AssertHex(string value, string parameterName)
    {
        foreach(char entry in value)
        {
            if (!Char.IsNumber(entry))
            {
                if (entry != 'a' && entry != 'A' && entry != 'b' && entry != 'B' 
                    && entry != 'c' && entry != 'C' && entry != 'd' && entry != 'D' && entry != 'e' && entry != 'E' && entry != 'f' && entry != 'F')
                {
                    throw new ArgumentException("Not a valid hexidecimal number", parameterName);
                }
            }
        }
    }

    public static void AssertNotNullOrEmpty(string value, string parameterName)
    {
        if (string.IsNullOrEmpty(value))
            throw new ArgumentNullException(parameterName);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM