循环左旋转算法的C# [英] Circular Left Rotation Algorithm in C#
问题描述
所以我有这个算法,它左右旋转
SO I have this algorithm that does left rotation
public static ushort RotateLeft(ushort value, int count)
{
int left = value << count;
int right = value >> (16 - count);
return (ushort)(left | right);
}
然而,这是不生产我想例如价值观,如果我有18的值时,左移1位它的结果应该是3,而是这只是增加了一个零结尾:
However this is not producing the values I want for example if I have a value of 18 when rotated left by 1 bit it the result should be 3 but instead this just adds a zero at the end:
这是什么样的算法做:
10010 18
100100 36
这就是我想要的:
10010 18
00101 3
该位应该被移出的符号位的位置(位0)进入至少显著比特位置(位15),以及,因此,没有比特被丢失。
The bits should be shifted out of the sign bit position (bit 0) enter the least significant bit position (bit 15) and, consequently, no bits are lost.
我想在这里说明什么: http://www.xgc.com/manuals/m1750-ada/m1750 /x2733.html
What I want is described here: http://www.xgc.com/manuals/m1750-ada/m1750/x2733.html
这是一个CRC算法,我想转换为C#
It's a CRC algorithm that I want to convert to C#
推荐答案
您code应该作如下更正。
Your code should be corrected as follows.
我添加了新的说法numberOfBits来位被旋转了presents数量。
I add new argument 'numberOfBits' to presents number of bits to be rotated.
public static ushort RotateLeft(ushort value, int numberOfBits int countToRotate)
{
countToRotate = countToRotate mod numberOfBits; // in case of rotate more than once.
ushort mask = -1 // 1s for all 16 bits.
mask = mask << numberOfBits;
int left = value << countToRotate; // rotate left
int right = left >> (numberOfBits); // move left-overflowed bits to right
return (ushort)((left | right) & mask);
}
这code正常工作,如果(numOfBits + countToRotate)LT; = 16
This code works correctly if (numOfBits+countToRotate)<=16.
这篇关于循环左旋转算法的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!