Perform a Bitwise Righ Rotation on a byte

Discussion in 'C Programming' started by trunsk14, Mar 21, 2008.

  1. trunsk14

    trunsk14

    Joined:
    Mar 12, 2008
    Messages:
    4
    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?
     
    trunsk14, Mar 21, 2008
    #1
    1. Advertising

  2. trunsk14

    trunsk14

    Joined:
    Mar 12, 2008
    Messages:
    4
    using assembly instructions like ROR or ROL is not allowed ;)
     
    trunsk14, Mar 21, 2008
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Will Clark

    360degree rotation in Java2D

    Will Clark, Aug 28, 2003, in forum: Java
    Replies:
    3
    Views:
    3,151
    Knute Johnson
    Sep 4, 2003
  2. Sheena
    Replies:
    1
    Views:
    397
    Harald Hein
    Oct 28, 2003
  3. hilz
    Replies:
    2
    Views:
    1,304
  4. Mark via JavaKB.com

    Java 2D: Image rotation

    Mark via JavaKB.com, Mar 19, 2005, in forum: Java
    Replies:
    0
    Views:
    804
    Mark via JavaKB.com
    Mar 19, 2005
  5. Chris
    Replies:
    6
    Views:
    2,470
    Daniel Pitts
    Jan 5, 2007
Loading...

Share This Page