【问题标题】:BitArray to zeros and onesBitArray 到零和一
【发布时间】:2018-08-30 02:41:30
【问题描述】:

我有这段代码...

string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);

代码正确地将字符串转换为 Bitarray。现在我需要将 BitArray 转换为零和一。
我需要使用零和一个变量进行操作(即不用于表示 [没有左零填充])。谁能帮帮我?

【问题讨论】:

    标签: c# bitarray


    【解决方案1】:

    你可以从BitArray得到0和1个integer数组。

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

    FIDDLE

    【讨论】:

      【解决方案2】:

      BitArray 类是在您的情况下用于按位运算的理想类。如果您想做布尔运算,您可能不想将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的:

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

      【讨论】:

      • +1,使用BitArray 类是一种更优雅的方式来执行按位运算,而不是在 BigInteger 上执行相同的操作
      • 嗯,你的回答似乎对我有用,但我有两个问题要问你,1-我可以用不同的方式处理位数组中的每个位,例如。 G。我对第一位做异或,对第二位做异或,对第三位做补码,依此类推。 ?? 2- 我可以声明位数组吗?
      【解决方案3】:

      如果您想对Byte[] 执行位运算,您可以使用BigInteger 类。

      1. 使用BigInteger类构造函数public BigInteger(byte[] value)将其转换为0和1。
      2. 对其执行按位运算。

        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

      有用的链接:BigInteger class

      Operators in BigInteger class

      【讨论】:

      • 不,我不想要布尔值,因为我需要对其进行按位和其他操作。但是位数组给了我(真假变量),不幸的是这对我不起作用。
      • 您想对字节或单个位中存在的每个位执行按位运算吗?简化的问题:您要遍历每个位(每个 0/1)还是每个字节?如果我理解错误,请纠正我
      • 我想对单个位中存在的每个位执行按位运算
      猜你喜欢
      • 2017-11-16
      • 2011-09-10
      • 2016-10-29
      • 2016-05-24
      • 2018-04-30
      • 2012-05-30
      • 2012-03-30
      • 2016-08-31
      • 2016-06-25
      相关资源
      最近更新 更多