我有这段代码。
string rand = RandomString(16);
byte[] bytes = Encoding.ASCII.GetBytes(rand);
BitArray b = new BitArray(bytes);代码正确地将字符串转换为位数组。现在我需要将BitArray转换为0和1。
我需要使用零和1变量进行操作(即没有左零填充的表示)。有人能帮我吗?
发布于 2018-03-21 05:44:28
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发布于 2018-03-21 05:14:31
如果要在上按位执行操作,可以使用BigInteger类。
BigInteger类构造函数public BigInteger(byte[] value)将其转换为0和1。BigInteger类支持BitWiseAnd和BitWiseOr
有用的链接:BigInteger类
发布于 2018-03-21 05:51:54
您可以从integer获得0和1个BitArray数组。
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]);
}小提琴
https://stackoverflow.com/questions/49398526
复制相似问题