-2

Im doing an assignment

  • asr - arithmetic shift right the bits of number1, number2 places to the right (see below)
  • rol - rotate the bits of number1, number2 places to the left (see below)
  • ror - rotate the bits of number1, number2 places to the right

Im having trouble figuring out how to do this part

here is what i have so far

int main()
{
    char n[90];
    char method[90];
    unsigned int num1;
    int methodlength;
    unsigned int num2;
    int d;
    unsigned int answer;

    printf("Type in an expression: ");

    gets(n);

    sscanf(n, "%x %s %x", &num1, method, &num2);



    if(strcmp(method, "asr") == 0)
    {
        printf("The answer is: %x", answer);
    }

    else if(strcmp(method, "rol") == 0)
    {
        printf("The answer is: %x", answer);
    }

    else if(strcmp(method, "ror") == 0)
    {
        printf("The answer is: %x", answer);
    }


}
  • What you *have so far* is nothing in relation to the assignment; assignments are intended to demonstrate your *learning*. You should make a fair attempt before soliciting help. – Clifford Aug 08 '14 at 08:16
  • @Clifford I asked not to include the rest of the assignment, see [the history](http://stackoverflow.com/posts/25198600/revisions) – HostileFork says dont trust SE Aug 08 '14 at 08:17
  • @HostileFork: That's not my point - the code fragment as it is now adds nothing to the question - its just a framework. The two *"(see below)"* bear no relation to anything below. The nub of this is how to perform ROL and ROR operations - every thing else is superfluous. – Clifford Aug 08 '14 at 09:27

2 Answers2

1

You can use bitmasking to play around bits.

You may find following links useful.
1. Wikipedia : Mask
2. Topcoder: Bitmasking

For example ROL can be done as

unsinged int arg = something;
unsigned int howmanytimes = some_other_thing;
unsigned int answer = (arg << howmanytimes) | (arg >> (sizeof(arg) * CHAR_BIT - howmanytimes));

After studying a little about masking, you should be able to understand the example and write the rest of the operations by your own. Still if you don't understand any specific thing, feel free to comment and ask.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • http://stackoverflow.com/questions/776508/best-practices-for-circular-shift-rotate-operations-in-c for a safer but still compiler-friendly version. – Peter Cordes Aug 17 '15 at 22:25
0

I don't think that there is a simple operation you can just use for this. You can implement it as a combination of a 'bitwise and' and a shift: For rotate left: save the first 2 bits of the number with & 0xc0000000, then shift left by 2, then replace the last bits of the number with the ones you saved.

See http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/bitshift.html for a more detailed explanation of bit shifting if you need it.

HSquirrel
  • 839
  • 4
  • 16