Bit rotate in C

Well, recently my professor just gave me an assignment to write some algorithm in C that allows you to shift the bits in binary, but instead of having the leftmost/rightmost bit disappear into oblivion, it appears on the other side of the bit

e.g. 00000101 shifted right would be 10000010 (in 8 bit)

Well, there’s probably a predefined function for this in C, but since I’m too lazy to google it, I’ve decided to simply write it by myself.

int shiftright(){
scanf(“%d”, &x);
if(x % 2 == 1){ //odd number with 1 as the rightmost bit
x = x >> 1;
x = x | 128; // adds 1 in the leftmost bit
}
else{ // even number with 0 as the rightmost bit
x = x >> 1;
}
return x;
}

int shiftleft(){
scanf(“%d”, &x);
if(x >= 128){ //1 as the leftmost bit
x = x << 1;
x = x & 255; // so that it stays in 8-bit
x = x | 1; // adds 1 in the rightmost bit
}
else{
x = x << 1;
}
return x;
}

There. It’s just a programming assignment, so of course it’s just an assignment-level program. Don’t expect too much from me! >_<

2 thoughts on “Bit rotate in C

  1. ckckkkckk.. bahkan ini ditulis juga..
    aditt,,aditt.. hahaha
    eh eh, ajarin gw dong.. parah banget nih strukdat, nol kosong banget gw..😦

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s