C# 将位数组设置为0和1

C# 将位数组设置为0和1,c#,bitarray,C#,Bitarray,我有这段代码 string rand = RandomString(16); byte[] bytes = Encoding.ASCII.GetBytes(rand); BitArray b = new BitArray(bytes); 该代码正确地将字符串转换为位数组。现在我需要将位数组转换为0和1。 我需要使用0和1变量进行操作(即,不用于表示perposes[没有左零填充])。有人能帮我吗?如果您想对Byte[]执行位操作,可以使用biginger类 使用biginger类构造函数公共b

我有这段代码

string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);
该代码正确地将字符串转换为位数组。现在我需要将位数组转换为0和1。

我需要使用0和1变量进行操作(即,不用于表示perposes[没有左零填充])。有人能帮我吗?

如果您想对
Byte[]
执行位操作,可以使用
biginger

  • 使用
    biginger
    类构造函数
    公共biginger(字节[]值)
    将其转换为0和1
  • 对其执行位操作

    string rand = "ssrpcgg4b3c";
    string rand1 = "uqb1idvly03";
    byte[] bytes = Encoding.ASCII.GetBytes(rand);
    byte[] bytes1 = Encoding.ASCII.GetBytes(rand1);
    BigInteger b = new BigInteger(bytes);
    BigInteger b1 = new BigInteger(bytes1);
    BigInteger result = b & b1;
    
  • BigInteger类支持BitWiseAnd和BitWiseOr

    有用链接:


    位数组
    类是在按位操作中使用的理想类。如果要执行布尔运算,您可能不想将
    BitArray
    转换为
    bool[]
    或任何其他类型。它高效地存储
    bool
    值(每个值1位),并为您提供执行逐位操作所需的方法

    BitArray.And(BitArray other)
    BitArray.Or(BitArray other)
    BitArray.Xor(BitArray other)
    用于布尔运算,
    BitArray.Set(int index,bool value)
    BitArray.Get(int index)
    用于处理单个值

    编辑

    您可以使用任何按位操作单独操纵值:

    bool xorValue = bool1 ^ bool2;
    bitArray.Set(index, xorValue);
    
    当然,您可以拥有
    位数组
    的集合:

    BitArray[] arrays = new BitArray[2];
    ...
    arrays[0].And(arrays[1]); // And'ing two BitArray's
    

    您可以从
    位数组
    获取0和1
    整数
    数组

                string rand = "yiyiuyiyuiyi";
                byte[] bytes = System.Text.Encoding.ASCII.GetBytes(rand);
                BitArray b = new BitArray(bytes);
    
                int[] numbers = new int [b.Count];
    
                for(int i = 0; i<b.Count ; i++)
                {
                    numbers[i] = b[i] ? 1 : 0;
                    Console.WriteLine(b[i] + " - " + numbers[i]);
                }
    
    string rand=“yiyiyiyiyiyiyiyiyiyi”;
    byte[]bytes=System.Text.Encoding.ASCII.GetBytes(rand);
    BitArray b=新的BitArray(字节);
    int[]数字=新的int[b.Count];
    
    对于(int i=0;iNo,我不想要布尔型,因为我需要对它进行逐位和其他操作不幸的是,这对我不起作用。你想对字节或单个位中的每个位执行逐位操作吗?简化问题:你想迭代每个位(每个0/1)或者每个字节?请纠正我,如果我理解错误,我想对单个位+1中的每个位执行位运算,使用
    位数组
    类是执行位运算的更优雅的方式,而不是对BigIntegerMM执行相同的运算,您的答案似乎对我很有用,但我有两个问题要问您,1-我可以用不同的方式对位数组中的每一位进行操作吗?例如,我对第一位进行异或运算,对第二位进行异或运算,对第三位进行补码运算。2-我可以声明位数组的数组吗?