首页 > 解决方案 > 我们可以随机访问一部分字节吗

问题描述

我们可以随机访问字节的一部分吗?我的意思是我可以在不使用 BitArray 并按字节访问的情况下随机访问三位。是否有可能从字节访问位,如果不是,为什么不能访问它,是否取决于任何标准

标签: c#memory

解决方案


您可以使用按位与 (&) 运算符从字节中读取特定位。我将通过使用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

推荐阅读