功能转换十六进制字符串BitArray C# [英] Function convert Hex String to BitArray C#

查看:552
本文介绍了功能转换十六进制字符串BitArray C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了以下功能的要求(十六进制转换成字符串BitArray),它会做。我不知道有关函数的效率,但现在我的主要问题是,在 Convert.ToInt64 函数的字节序的具体的。当这个被移植到备用芯片组,我们将得到不同的结果(或例外)。因此,谁能想到另一种方式来做到这一点的转换?

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

我删除了大部分的错误/异常处理保持这个大小使PLZ原谅。

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

这篇关于功能转换十六进制字符串BitArray C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆