我正在K&R上学习C,我解决了练习2.08:
编写一个函数
rightrot(x,n),返回按n位置旋转到右侧的整数x的值。
我已经用一些位模式测试了我的代码,它看起来很有效,但我不确定这个解决方案是否涵盖了所有可能的情况。
你觉得这个代码怎么样?
unsigned rightrot(unsigned x, int n)
{
int size;
unsigned y;
size = 0;
y = x;
while (y != 0) {
y = y << BYTESIZE;
size++;
}
size = size * BYTESIZE;
return (x << (size-n)) | (x >> n);
}这是主要的
#include <stdio.h>
#define BYTESIZE 8
unsigned rightrot(unsigned x, int n);
int main(void)
{
unsigned x;
int n;
x = 0x23acb;
n = 2;
printf("%x\n", rightrot(x, n));
return 0;
}发布于 2012-01-29 03:55:50
@William有最佳的解决方案。
但是,关于您的代码的一些评论:
// There is already a macro that defines the number of bits
// in a byte it is called CHAR_BIT
#define BYTESIZE 8
// Initialize variables as you declare them
int size;
unsigned y;
// You can find the number of bytes in an object using
// sizeof(<expression>)
while (y != 0) {
y = y << BYTESIZE;
size++;
}
// Thus the number of bits is:
// sizeof(y) * CHAR_BIT
size = size * BYTESIZE;
// The result is the same.
return (x << (size-n)) | (x >> n);发布于 2012-01-28 14:17:04
不是这样的吗?
#include <limits.h> /* for CHAR_BIT */
unsigned
rotate_right(unsigned x, int n)
{
int left_shift = ((sizeof x) * CHAR_BIT) - n;
return x<<left_shift | x>>n;
}https://codereview.stackexchange.com/questions/8390
复制相似问题