Perform a Bitwise Righ Rotation on a byte

Joined
Mar 12, 2008
Messages
4
Reaction score
0
Hey people! the challenge is the following (kinda homework :p):

given a byte, rotate it (not shift) n positions to the right.
Cannot use loops.

My solution is:

Code:
#include <stdio.h>

void print_byte(const unsigned char);

int main()
{
    unsigned char right_mask, left_mask, byte, output;
    unsigned int input; //used to store the byte given by the user
    int pos; //times to rotate

    printf("Enter a byte, in Base 10 format (example: 75): ");
    scanf("%u", &input);
    printf("How many times shall I rotate this byte: ");
    scanf("%d", &pos);

    pos %= 8;

    right_mask  = (0x01 << pos) - 1;
    left_mask = ~right_mask;

    byte = (unsigned char)input;

    output = ((byte & left_mask) >> pos) + ((byte & right_mask) << (8 - pos));

    print_byte(output);
    return 0;
}

void print_byte(const unsigned char byte)
{
    unsigned int mask = 256;
    while( (mask >>= 1) != 0 )
        putchar( (byte & mask)?'1':'0' );
}


Also, just wondering, what's the most efficient way to print a byte in binary format without using loops?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,814
Latest member
SpicetreeDigital

Latest Threads

Top