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

发布于 2024-10-04 09:54:20 字数 982 浏览 8 评论 0原文

我创建了以下函数,它将按要求执行(将十六进制字符串转换为 BitArray)。我不确定该函数的效率,但我现在的主要问题是 Convert.ToInt64 函数是特定于字节序的。当将其移植到备用芯片组时,我们将得到不同的结果(或例外)。那么有人能想到另一种方法来进行这种转换吗???

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 created the following function which will do as requested (convert HEX string to 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. 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不语却知心 2024-10-11 09:54:20

这是一个简单的答案,应该适用于任何长度的字符串:

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

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;
}
枯叶蝶 2024-10-11 09:54:20

试试这个:

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

Try this:

var int64 = Int64.Parse(hexData, NumberStyles.HexNumber);
var bytes = BitConverter.GetBytes(int64);
var bitArray = new BitArray(bytes);
我只土不豪 2024-10-11 09:54:20

我还没有测试过这个(认为它是伪代码),但它会很快:

    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];
    }
}

还有守卫:

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

I haven't tested this (consider it pseduo code), but it would be fast:

    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);
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文