byte[] 左移和右移

public static class ex
{
    public static byte[] RightShift(this byte[] ba, int n)
    {
        if (n < 0)
        {
            return ba.LeftShift(Math.Abs(n));
        }
        byte[] ba2 = null;
        ba2 = ba.Clone() as byte[];
        int loop = (int)Math.Ceiling(n / 8.0);
        byte tempByte = 0;
        byte tempByte2 = 0;
        byte Header = 0;

        for (int i = 0; i < loop; i++)
        {
            var tempN = i + 1 == loop ? n % 8 : 8;
            if (tempN == 0 && n != 0)
            {
                tempN = 8;
            }
            for (int j = 0; j < ba.Length; j++)
            {
                if (j == 0)
                {
                    Header = (byte)((ba2.Last() & ((byte)(Math.Pow(2, tempN) - 1))) << (8 - tempN));
                    tempByte = (byte)((ba2[j] & ((byte)(Math.Pow(2, tempN) - 1))) << (8 - tempN));
                    ba2[j] >>= tempN;
                }
                else
                {
                    tempByte2 = (byte)((ba2[j] & ((byte)(Math.Pow(2, tempN) - 1))) << (8 - tempN));
                    ba2[j] >>= tempN;
                    ba2[j] |= tempByte;
                    tempByte = tempByte2;
                    if (j + 1 == ba.Length)
                    {
                        ba2[0] |= Header;
                    }
                }
            }
        }
        return ba2;
    }
    public static byte[] LeftShift(this byte[] ba, int n)
    {
        if (n < 0)
        {
            return ba.RightShift(Math.Abs(n));
        }
        byte[] ba2 = null;
        ba2 = ba.Clone() as byte[];
        int loop = (int)Math.Ceiling(n / 8.0);
        byte tempByte = 0;
        byte tempByte2 = 0;
        byte Header = 0;

        for (int i = 0; i < loop; i++)
        {
            var tempN = i + 1 == loop ? n % 8 : 8;
            if (tempN == 0 && n != 0)
            {
                tempN = 8;
            }
            for (int j = 0; j < ba.Length; j++)
            {
                if (j == 0)
                {
                    Header = (byte)(ba2.First() & ((byte)(Math.Pow(2, tempN) - 1) << (8 - tempN)));
                    tempByte = (byte)(ba2[ba.Length - 1 - j] & ((byte)(Math.Pow(2, tempN) - 1) << (8 - tempN)));
                    ba2[ba.Length - 1 - j] <<= tempN;
                }
                else
                {
                    tempByte2 = (byte)(ba2[ba.Length - 1 - j] & ((byte)(Math.Pow(2, tempN) - 1) << (8 - tempN)));
                    ba2[ba.Length - 1 - j] <<= tempN;
                    ba2[ba.Length - 1 - j] |= (byte)(tempByte >> (8 - tempN));
                    tempByte = tempByte2;
                    if (j + 1 == ba.Length)
                    {
                        ba2[j] |= (byte)(Header >> (8 - tempN));
                    }
                }
            }
        }
        return ba2;
    }

}

猜你喜欢

转载自www.cnblogs.com/nocanstillbb/p/10573776.html