Hey people! the challenge is the following (kinda homework ):
given a byte, rotate it (not shift) n positions to the right.
Cannot use loops.
My solution is:
Also, just wondering, what's the most efficient way to print a byte in binary format without using loops?
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?