旋转的任意整数位用C [英] Rotating bits of any integer in C
问题描述
传递一个整数2这个函数,然后返回一个整数,也就是4
X = 2;
X = rotateInt(L中,x,1);
(由1位左移)
例如:
00000010 - >旋转由左1 - > 00000100
但如果我通过这样的:
X = rotateInt('R',X,3);
将返回64,01000000
下面是code,有人可以纠正错误...谢谢
INT rotateInt(字符方向,无符号整型的x,int y)对
{
unsigned int类型面膜= 0;
INT NUM = 0,结果为0;
INT I; 对于(i = 0; I< Y;我++)
{
如果(方向=='R')
{
如果((X安培; 1)== 1)
X =(X ^ 129);
其他
X = X>> 1;
}
否则如果(方向=='L')
{
如果((X&放大器; 128)== 1)
X =(X ^ 129);
其他
X = X&所述;&下; 1;
}
}
结果=(结果^ X);
返回结果;
}
所以,我假设你知道什么是左,右的变化是。并且知道算术和逻辑移位之间的差异。
仅C具有算术移位。它不这样做逻辑移位,也不做旋转。好吧,我撒谎了,C做逻辑移位无符号整数。
有一个旋转确实不错,正是:它是一样的,当你转移过去数的末尾,除了逻辑移位,数字环绕到另一边。例如:
0010
右键旋转时, 0001
。如果右键旋转一次,你会得到 1000
。你看,包裹 1
周围,或旋转,以整数的另一边。
左旋转是相似的: 0100
左旋 1000
左旋 0001
左旋 0010
等。
请注意,旋转不保留符号位的算术右移会。
所以,C只有算术移位。所以,你必须手动落实旋转的一部分。因此,采取左旋转。你会想:
- 捕捉最左边的位的值。 (它是一个0或1?)
- 请左移
- 将最右边的位 - 这是我们在步骤1中(需要被围绕其旋转)为正确值的基础上,我们从步骤1中拍摄 谈到了一点。
您应该能够找出一个类似的方法右旋转。
好运!
Pass a integer 2 to this function and then return a integer which is 4
x = 2;
x = rotateInt('L', x, 1);
(left shift the bits by 1)
Example: 00000010 -> rotate left by 1 -> 00000100
but if I pass this:
x = rotateInt('R', x, 3);
it will return 64, 01000000
Here is the code, can someone correct the error... thanks
int rotateInt(char direction, unsigned int x, int y)
{
unsigned int mask = 0;
int num = 0, result = 0;
int i;
for (i = 0; i < y; i++)
{
if (direction == 'R')
{
if ((x & 1) == 1)
x = (x ^ 129);
else
x = x >> 1;
}
else if (direction == 'L')
{
if ((x & 128) == 1)
x = (x ^ 129);
else
x = x << 1;
}
}
result = (result ^ x);
return result;
}
So, I'll assume you know what right and left shifts are. And that you know the difference between arithmetic and logical shifts.
C only has arithmetic shifts. It doesn't do logical shifts, nor does it do rotates. okay I lied, C does logical shifts on unsigned ints.
A rotate does, well, exactly that: it's the same as a logical shift, except when you shift past the end of the number, the digits "wrap around" to the other side. For example
0010
right-rotated is 0001
. If you right-rotate again, you get 1000
. See, the 1
wrapped around, or rotated, to the other side of the integer.
The left rotate is similar: 0100
left rotate 1000
left rotate 0001
left rotate 0010
etc.
Note that rotates don't keep the sign bit as an arithmetic right-shift would.
So, C only has arithmetic shifts. So you have to implement the "rotate" part manually. So, take a left-rotate. You would want to:
- Capture the value of the left-most bit. (is it a 0 or 1?)
- Do a left-shift
- Set the right-most bit - which is the bit we talked about in step 1 (which needs to be rotated around) to the correct value, based on what we captured from step 1.
You should be able to figure out a similar method for right rotates.
good luck!
这篇关于旋转的任意整数位用C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!