首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Bit旋转练习

Bit旋转练习
EN

Code Review用户
提问于 2012-01-28 10:52:33
回答 2查看 2K关注 0票数 5

我正在K&R上学习C,我解决了练习2.08:

编写一个函数rightrot(x,n),返回按n位置旋转到右侧的整数x的值。

我已经用一些位模式测试了我的代码,它看起来很有效,但我不确定这个解决方案是否涵盖了所有可能的情况。

你觉得这个代码怎么样?

代码语言:javascript
复制
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);
}

这是主要的

代码语言:javascript
复制
#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;
}
EN

回答 2

Code Review用户

回答已采纳

发布于 2012-01-29 03:55:50

@William有最佳的解决方案。

但是,关于您的代码的一些评论:

代码语言:javascript
复制
// 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);
票数 3
EN

Code Review用户

发布于 2012-01-28 14:17:04

不是这样的吗?

代码语言:javascript
复制
#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;
}
票数 6
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/8390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档