Some time ago, I encoded these two functions, the first shifted the byte [] by the specified number of bits to the left, and the second did the same on 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, then I will edit my post for clarification ...
source share