0

No loops are allowed. The only operators allowed are ~ & ^ | + << >> !

Rotate x to the right by 4.

Examples: rotate4(0x87654321) = 0x18765432

Max ops: 12

int rotate4(int x){
    CODE

I have

int rotate4(int x){
    return (x << 28) | (x >> 4);

This is outputting a negative number that seems to be correct, but negative.

Test: Answer should be 134217728[0x80000000]

My Answer is -134217728[0xf8000000]

My though process is:

x << moves the 4 LSB code to the left 28 spaces meaning the 4 LSB will be left in the MSB position.

x >> 4 drops off the 4 LSB so that the 4 MSB are 0s.

Is my code producing the wrong result because it is right shifting arithmetically?

Mat
  • 202,337
  • 40
  • 393
  • 406
Aima
  • 17
  • 2
  • 2
    When it comes to: **"The result of E1 >> E2"** the standard says: **" If E1 has a signed type and a negative value, the resulting value is implementation-defined."** In other words... you can get any result - no one can tell. Use unsigned types instead.... – Support Ukraine Sep 30 '22 at 05:19
  • What happens if you change `int` to `unsigned`? – hyde Sep 30 '22 at 05:22
  • @SupportUkraine This appears to be a task in CS:APP where the types can't be changed. Need to work around signedness restriction. – iBug Sep 30 '22 at 05:23
  • The size of `int` is not set in stone, so the result is not either. If you used a signed type, then the example `rotate4(0x87654321) = 0x18765432` is simply not true. The assignment seems to be poorly defined. – Cheatah Sep 30 '22 at 05:29
  • 1
    @iBug well, I pretty sure this can't be done in a standard compliant way with predictable result if the type is `int`. – Support Ukraine Sep 30 '22 at 05:31
  • See https://stackoverflow.com/questions/11644362/are-the-results-of-bitwise-operations-on-signed-integers-defined – Support Ukraine Sep 30 '22 at 05:35
  • 2
    Even homework specifications have undefined behavior in C. – Kaz Sep 30 '22 at 06:45
  • A similar homework exercise was discussed here: https://stackoverflow.com/questions/3928659/rotating-bits-of-any-integer-in-c – nielsen Sep 30 '22 at 07:51

1 Answers1

0

Left shifting data in a signed int beyond bit 30 invokes undefined behavior - you'll be shifting data into the sign bit. This is one of many reasons why we should pretty much never use signed operands to the bitwise operators.

In your case, you can't even store 0x87654321 inside an int because it's already too large before the shift.

Change to unsigned int or better yet uint32_t. Then this should give the result 0x18765432.

Lundin
  • 195,001
  • 40
  • 254
  • 396