HiveBrain v1.2.0
Get Started
← Back to all entries
patterncMinor

Bit rotations exercise

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
rotationsbitexercise

Problem

I'm studying C on K&R and I solved exercise 2.08:


Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n positions

I've tested my code with some bit patterns and it seems to work, but I'm not sure that this solution covers all possible cases.

What do you think about this code?

unsigned rightrot(unsigned x, int n)
{   
    int size;
    unsigned y;

    size = 0;
    y = x;

    while (y != 0) {
    y = y > n);
}


Here is the main

#include 

#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;
}

Solution

Isn't it something like this?

#include  /* for CHAR_BIT */

unsigned
rotate_right(unsigned x, int n)
{
    int left_shift = ((sizeof x) * CHAR_BIT) - n;
    return x>n;
}

Code Snippets

#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;
}

Context

StackExchange Code Review Q#8390, answer score: 6

Revisions (0)

No revisions yet.