简体   繁体   中英

Using bit manipulations, return word with all odd-numbered bits set to 1

This problem is part of a larger coding project in my coding class, intro to C. The goal of the project is to get used to bit manipulations and floating point. To do so, it presents a number of problems under restrictions. Here is this problem:

 /* 
 * OddBits - return word with all odd-numbered bits set to 1
 *   Legal operations: | <<
 *   Max operations: 6
 *   Rating: 2
 */

As you can see, for his problem, I can only use | and <<. There are some other assumptions as well not listed in this problem. They are; no constants bigger than 0xFF, assume 32 bit machine, and no statements such as do, if, while, or else. Also I can't cast variables into unsigned.

Here is my current code:

int OddBits(void) {
  int x;
  return (x | (x << 1)) | ((x << 1) << 1);
}

The error message thrown by the grading software is:

ERROR: Test OddBits() failed...
...Gives 0[0x0]. Should be -1431655766[0xaaaaaaaa]

I'd really appreciate if someone could explain where I went wrong with my methodology and how I could fix it.

I hope, this will help:

int OddBits(void) {
  return 0x55 | (0x55 << 8) | (0x55 << 16) | (0x55 << 24);
}

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