C中任何整数的旋转位 [英] Rotating bits of any integer in C
问题描述
将一个整数 2 传递给该函数,然后返回一个整数 4
Pass a integer 2 to this function and then return a integer which is 4
x = 2;
x = rotateInt('L', x, 1);
(左移1位)
示例:00000010 -> 向左旋转 1 -> 00000100
Example: 00000010 -> rotate left by 1 -> 00000100
但如果我通过了:
x = rotateInt('R', x, 3);
它将返回 64, 01000000
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 只有算术移位.它不做逻辑移位,也不做旋转.好吧,我撒谎了,C 对无符号整数进行逻辑移位.
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
右旋为 0001
.如果你再次右转,你会得到 1000
.看,1
环绕或旋转到整数的另一侧.
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.
左旋类似:0100
左旋1000
左旋0001
左旋0010
等
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.
所以,C 只有算术移位.所以你必须手动实现旋转"部分.所以,左转.你会想要:
So, C only has arithmetic shifts. So you have to implement the "rotate" part manually. So, take a left-rotate. You would want to:
- 捕获最左边位的值.(是 0 还是 1?)
- 左移
- 根据我们从第 1 步捕获的内容,将最右边的位 - 我们在第 1 步中讨论的位(需要旋转)设置为正确的值.
您应该能够找出类似的右旋方法.
You should be able to figure out a similar method for right rotates.
祝你好运!
这篇关于C中任何整数的旋转位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!