BitArray 到零和一
BitArray to zeros and ones
我有这段代码...
string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);
代码正确地将字符串转换为位数组。现在我需要将 BitArray 转换为零和一。
我需要使用 zeros 和 ones 变量进行操作(即不用于表示 [没有左零填充])。谁能帮帮我?
如果要对Byte[]
执行位运算,可以使用BigInteger
class。
- 使用
BigInteger
class构造函数public BigInteger(byte[] value)
将其转化为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 class 支持 BitWiseAnd 和 BitWiseOr
有帮助link:BigInteger class
BitArray
class 是理想的 class 在您的情况下用于按位运算。如果您想进行布尔运算,您可能不想将 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);
你当然可以有 collection 个 BitArray
:
BitArray[] arrays = new BitArray[2];
...
arrays[0].And(arrays[1]); // And'ing two BitArray's
您可以从 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]);
}
我有这段代码...
string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);
代码正确地将字符串转换为位数组。现在我需要将 BitArray 转换为零和一。
我需要使用 zeros 和 ones 变量进行操作(即不用于表示 [没有左零填充])。谁能帮帮我?
如果要对Byte[]
执行位运算,可以使用BigInteger
class。
- 使用
BigInteger
class构造函数public BigInteger(byte[] value)
将其转化为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 class 支持 BitWiseAnd 和 BitWiseOr
有帮助link:BigInteger class
BitArray
class 是理想的 class 在您的情况下用于按位运算。如果您想进行布尔运算,您可能不想将 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);
你当然可以有 collection 个 BitArray
:
BitArray[] arrays = new BitArray[2];
...
arrays[0].And(arrays[1]); // And'ing two BitArray's
您可以从 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]);
}