Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Bit-shifting a byte array by N bits

Hello quick question regarding bit shifting

I have a value in HEX: new byte[] { 0x56, 0xAF }; which is 0101 0110 1010 1111

I want to the first N bits, for example 12.

Then I must right-shift off the lowest 4 bits (16 - 12) to get 0000 0101 0110 1010 (1386 dec).

I can't wrap my head around it and make it scalable for n bits.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Sometime ago i coded these two functions, the first one shifts an byte[] a specified amount of bits to the left, the second does the same to the right:

Left Shift:

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;
}

Right Shift:

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;
}

If you need further explanation please comment on this, i will then edit my post for clarification...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...