Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

So I found this code online and it supposed to shift to the left. Looking at the

ID: 3752686 • Letter: S

Question

So I found this code online and it supposed to shift to the left. Looking at the function, there is a line there that it will shift to the right. Why do you have to do that? Also, why would you use operator OR when returning. Note that this code works, the problem is just dont understand. If you guys explain this to me that would be great.

#include <stdio.h>

/*

* Do rotating left shift. Assume 0 <= n < w

* Examples when x = 0x12345678 and w = 32:

* n=4 -> 0x23456781, n=20 -> 0x67812345

*/

unsigned rotate_left(unsigned x, int n)

{

    int w = sizeof(unsigned) << 3;

    unsigned msb = x >> (w-n);

    unsigned new_msb = x << n;

    return new_msb | msb;

}

int main(int argc, char **argv)

{

    printf("%.8x ", rotate_left(0x12345678, 4));

    printf("%.8x ", rotate_left(0x12345678, 20));

    printf("%.8x ", rotate_left(0x12345678, 0));

}

Explanation / Answer

please give thumbs up, thanks

#include <stdio.h>

/*

* Do rotating left shift. Assume 0 <= n < w

* Examples when x = 0x12345678 and w = 32:

* n=4 -> 0x23456781, n=20 -> 0x67812345

*/

unsigned rotate_left(unsigned x, int n)

{

//this part is generation number 32 which will be used to know what is the number of bits tye "unsigned" have.

//we know 32 bits are there so that is generated by system, we are not assuming by ourself.

int w = sizeof(unsigned) << 3;

//if we want to do left shift for n times that means the leftmost n bits should be saved.

//so we need to remove (w-n) rightmost bits from number, that why we are doing right shift to get get left rorated part of number in rightmost position

unsigned msb = x >> (w-n);

//now we nee to remove rightmost n bits from actual number, because at that position we will insert the previous calculated msb

unsigned new_msb = x << n;

//since rotated left part is available in msb and Right part is avalable in new_msb, so to concatonate, we are doing or opearation

return new_msb | msb;

}

int main(int argc, char **argv)

{

printf("%.8x ", rotate_left(0x12345678, 4));

printf("%.8x ", rotate_left(0x12345678, 20));

printf("%.8x ", rotate_left(0x12345678, 0));

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote