位移N位

Bob*_*bby 1 c# bit-manipulation bit-shift

你好关于位移的快速问题

我有一个HEX = new byte [] {0x56,0xAF}的值;

这是0101 0110 1010 1111

我想要前n位,例12

然后将剩下的4(16-12)转移到0000 0101 0110 1010(1386 dec)

我无法绕过它并使其可扩展到n位.

谢谢!

haz*_*eal 6

前段时间我编写了这两个函数,第一个函数将一个byte []向左移动指定的位数,第二个向右移动:

左移:

public byte[] ShiftLeft(byte[] value, int bitcount)
{
    byte[] temp = new byte[value.Length];
    if (bitcount >= 8)
    {
        Array.Copy(value, bitcount / 8, temp, 0, temp.Length - (bitcount / 8));
    }
    else
    {
        Array.Copy(value, temp, temp.Length);
    }
    if (bitcount % 8 != 0)
    {
        for (int i = 0; i < temp.Length; i++)
        {
            temp[i] <<= bitcount % 8;
            if (i < temp.Length - 1)
            {
                temp[i] |= (byte)(temp[i + 1] >> 8 - bitcount % 8);
            }
        }
    }
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

右移:

public byte[] ShiftRight(byte[] value, int bitcount)
{
    byte[] temp = new byte[value.Length];
    if (bitcount >= 8)
    {
        Array.Copy(value, 0, temp, bitcount / 8, temp.Length - (bitcount / 8));
    }
    else
    {
        Array.Copy(value, temp, temp.Length);
    }
    if (bitcount % 8 != 0)
    {
        for (int i = temp.Length - 1; i >= 0; i--)
        {
            temp[i] >>= bitcount % 8;
            if (i > 0)
            {
                temp[i] |= (byte)(temp[i - 1] << 8 - bitcount % 8);
            }
        }
    }
    return temp;
}
Run Code Online (Sandbox Code Playgroud)

如果您需要进一步说明,请对此进行评论,然后我会编辑我的帖子以澄清...