是否有一个函数在C#中为字节数组做圆形位移?

我似乎无法找到是否有内置的方法来执行字节数组的循环位移,C的ROL和ROR用于单个字节?

让我解释一下,比方说,我有一个数组(二进制):

[0] = 11001110 [1] = 01000100 [2] = 10100001 

然后如果我想做ROL_Array(1 bit)或向左移动1位,我会得到:

 [0] = 10011100 [1] = 10001001 [2] = 01000011 

或者,如果我想做ROR_Array(2 bits)或向右移动2位,我会得到:

 [0] = 00110011 [1] = 01010001 [2] = 10101000 

这并不像你想象的那么简单。 这个线程关闭之前是一个快速版本:

 public static byte[] ROL_ByteArray(byte[] arr, int nShift) { //Performs bitwise circular shift of 'arr' by 'nShift' bits to the left //RETURN: // = Result byte[] resArr = new byte[arr.Length]; if(arr.Length > 0) { int nByteShift = nShift / (sizeof(byte) * 8); //Adjusted after @dasblinkenlight's correction int nBitShift = nShift % (sizeof(byte) * 8); if (nByteShift >= arr.Length) nByteShift %= arr.Length; int s = arr.Length - 1; int d = s - nByteShift; for (int nCnt = 0; nCnt < arr.Length; nCnt++, d--, s--) { while (d < 0) d += arr.Length; while (s < 0) s += arr.Length; byte byteS = arr[s]; resArr[d] |= (byte)(byteS << nBitShift); resArr[d > 0 ? d - 1 : resArr.Length - 1] |= (byte)(byteS >> (sizeof(byte) * 8 - nBitShift)); } } return resArr; } 

这是一个测试:

 byte[] arr = new byte[] { Convert.ToByte("11001110", 2), Convert.ToByte("01000100", 2), Convert.ToByte("10100001", 2), }; byte[] arr2 = Auth.ROL_ByteArray(arr, 1); string sss = ""; for (int i = 0; i < arr2.Length; i++) sss += Convert.ToString(arr2[i], 2) + ", "; Debug.WriteLine(sss);