Is there a function for cyclic bit shift for a byte array in C #?

It seems I can not find if there is a built-in way to perform a cyclic bit shift of a byte array that C ROL and ROR are used for one byte?

Let me explain, say, I have an array (in binary format):

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

and then if I want to do ROL_Array(1 bit) or move the bit 1 bit to the left, I would get:

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

or, if I want to do ROR_Array(2 bits) or move the bits 2 bits to the right, I would get:

 [0] = 00110011 [1] = 01010001 [2] = 10101000 
+4
source share
1 answer

It is not as easy as you think. Here is a quick version before closing this thread:

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

and here is the test:

 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); 
+3
source

All Articles