在C#中将BitArray中的所有位值取反

2023年 8月 27日 33.4k 0

在C#中将BitArray中的所有位值取反

A BitArray is a collection of Boolean values represented as a series of 1’s and 0’s. It is often used to store and manipulate binary data efficiently. In C#, the BitArray class is part of the System. Collections namespace, and it allows you to manipulate the individual bits in the array using bitwise operators.

反转位数组中的所有位值

在C#中,要反转BitArray中的所有位值,可以使用异或(XOR)运算符(^)与数字1一起使用。该运算符在比较的位不同时返回值1,如果它们相同则返回值0。通过将此运算符应用于BitArray中的每个位,可以反转所有位值。

Example 1

的中文翻译为:

示例1

The following example demonstrates how to invert all bit values in a BitArray in C#

算法

  • 步骤 1 - 创建一个新的 BitArray 来存储反转的值。

  • 步骤 2 - 循环遍历原始 BitArray 中的每个位。

  • 步骤 3 − 使用位求反运算符(~)反转每个位的值。

  • 步骤 4 - 将反转的值存储在新的 BitArray 中。

  • 第5步 - 返回新的BitArray。

using System;
using System.Collections;
class Program{
static void Main(string[] args){
// Create a new BitArray with some initial values
BitArray bits = new BitArray(new[] { true, false, true, false });

// Invert all the bit values using XOR with 1
for (int i = 0; i < bits.Length; i++){
bits[i] ^= true;
}

// Print the inverted bit values
for (int i = 0; i < bits.Length; i++){
Console.Write(bits[i] ? "1" : "0");
}
Console.ReadLine();
}
}

登录后复制

输出

当你运行上面的代码输出时,这个输出对应于原始 BitArray(1010)的反转位值。

0101

登录后复制

Example 2

的中文翻译为:

示例2

下面的示例演示了在C#中反转BitArray中的所有位值

算法

  • Step 1 − Create a BitArray object with the desired size.

  • 第二步 - 循环遍历BitArray中的每个索引。

  • 步骤 3 - 使用 BitArray.Set 方法将当前索引处的值取反,参数为索引和当前索引的取反值。

using System;
using System.Collections;
class Program {
static void Main(string[] args) {
int size = 8;
BitArray bits = new BitArray(size);
for (int i = 0; i < size; i++) {
bits[i] = (i % 2 == 0);
}
Console.WriteLine("Before inversion:");
PrintBits(bits);
InvertBits(bits);
Console.WriteLine("After inversion:");
PrintBits(bits);
}
static void InvertBits(BitArray bits) {
for (int i = 0; i < bits.Count; i++) {
bits.Set(i, !bits[i]);
}
}
static void PrintBits(BitArray bits) {
for (int i = 0; i < bits.Count; i++) {
Console.Write(bits[i] ? "1" : "0");
}
Console.WriteLine();
}
}

登录后复制

输出

Before inversion:
01010101
After inversion:
10101010

登录后复制

结论

在C#中,将BitArray中的所有位值取反是一个简单的任务,可以使用异或运算符与值1来完成。这种技术在处理二进制数据时非常有用,可以帮助您高效地操作数组中的各个位。

以上就是在C#中将BitArray中的所有位值取反的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

如何删除WordPress中的所有评论
检查WordPress服务器磁盘使用情况的7种简便方法(查找大文件和数据)
如何更改WordPress常量FS_METHOD
如何为区块编辑器、Elementor等构建WordPress文章模板
如何彻底地删除WordPress主题及相关内容
如何使用WordPress搭建一个内网

发布评论