简体   繁体   中英

Right rotation of a 16-bit non-negative number?

I'm working on a method in which I need to perform a right rotation. For instance, I have the binary number 0101110111000111, and after the method is performed, the result should be 1010111011100011. A 16-bit non-negative number is passed as the parameter, and this parameter value will have all the bits moved to the right by 1 bit position and with the low-order bit moved to the high-order position (like the example above).

Here is the code I have written. I converted 0101110111000111 to the decimal value of 24007.

#include <stdlib.h>
#include <stdio.h>

unsigned int rotateRight(unsigned int x);

int main(int argc, char **argv) {
  unsigned int n = 24007; 
  printf("%d\n", rotateRight(n, d)); 
  return 0; 
} 

/*Function to right rotate n by d bits*/
unsigned int rotateRight(unsigned int x) {
  return (x >> 1) | (x << (16-1));
}

My expected result should be the value of 44771, because that is the decimal equivalent to 1010111011100011. However, when I run this program, I get 786673379. Could someone explain why this is happening, and how I could improve my rotation function so I can get the correct answer?

(x << (16-1) shifts the entire 16-bit quantity 15 places to the left and prepends it to the x >> 1 . Since int can hold a 32-bit value and therefore doesn't truncate your calculation, you get a 31-bit value as a result.

ie

x = 0101 1101 1100 0111
x >> 1 = 0010 1110 1110 0011
x << (16 -1) = 0010 1110 1110 0011 1000 0000 0000 0000

=> (x >> 1) | (x << (16-1))
    = 0101110111000111010111011100011 (binary)
    = 786673379 (decimal)

A solution would be:

unsigned int rotateRight(unsigned int x) {
  return ((x >> 1) | (x << (16-1))) & 0xffff;
}

ie do the calculation you're already doing, but keep only the lowest 16 bits.

Alternatively you could use a type like uint16_t to ensure that larger numbers are automatically truncated, subject to your feelings about implicit type conversions and explicit type conversion syntax.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM