c# - 我们可以随机访问一部分字节吗
问题描述
我们可以随机访问字节的一部分吗?我的意思是我可以在不使用 BitArray 并按字节访问的情况下随机访问三位。是否有可能从字节访问位,如果不是,为什么不能访问它,是否取决于任何标准
解决方案
您可以使用按位与 (&) 运算符从字节中读取特定位。我将通过使用0b
前缀给出一些示例,在 C# 中,它允许您在代码中编写二进制文字。
所以假设你有以下字节值:
byte val = 0b10010100; // val = 148 (in decimal)
byte testBits = 0b00000100; // set ONLY the BITS you want to test here...
if ( val & testBits != 0 ) // bitwise and will return 0 if the bit is NOT SET.
Console.WriteLine("The bit is set!");
else
Console.WriteLine("The bit is not set....");
这是一种测试给定字节中任何位的方法,该方法使用应用于数字 1的左移运算符来生成一个二进制数,该二进制数可用于针对给定字节中的任意位进行测试:
public static int readBit(byte val, int bitPos)
{
if ((val & (1 << bitPos)) != 0)
return 1;
return 0;
}
您可以使用此方法打印给定字节中设置了哪些位:
byte val = 0b10010100;
for (int i = 0; i < 8; i++)
{
int bitValue = readBit(val, i);
Console.WriteLine($"Bit {i} = {bitValue}");
}
上面代码的输出应该是:
Bit 0 = 0
Bit 1 = 0
Bit 2 = 1
Bit 3 = 0
Bit 4 = 1
Bit 5 = 0
Bit 6 = 0
Bit 7 = 1
推荐阅读
- bitmap - 在 MIPS 中绘制圆以位图显示
- python - 如何在 Python 中打印多个字符串中的多个变量
- javascript - ValueError:视图未返回 HttpResponse 对象。它返回 None 。(Django/ImgKit)
- c - C中的整数算术溢出预防
- android - Firebase 身份验证:在身份验证期间没有收到来自 FirebaseUser 的电子邮件
- html - 从 Vue 调用 laravel 路由
- c# - 如何按部分将 JSON 文件反序列化为 C# 对象
- php - 按钮和表格下拉列表显示 Laravel 8 中的重复值
- kubernetes-helm - helm 语法 {{ something }} 和 {{- something }} 有什么区别?
- sql - 雪花 Where 子句没有过滤?