- #1
opt!kal
- 19
- 0
Homework Statement
Each "Expr" is an expression using ONLY the following:
1. Integer constants 0 through 255 (0xFF), inclusive. You are
not allowed to use big constants such as 0xblackff.
2. Function arguments and local variables (no global variables).
3. Unary integer operations ! ~
4. Binary integer operations & ^ | + << >>
Some of the problems restrict the set of allowed operators even further.
Each "Expr" may consist of multiple operators. You are not restricted to
one operator per line.
You are expressly forbidden to:
1. Use any control constructs such as if, do, while, for, switch, etc.
2. Define or use any macros.
3. Define any additional functions in this file.
4. Call any functions.
5. Use any other operations, such as &&, ||, -, or ?:
6. Use any form of casting.
You may assume that your machine:
1. Uses 2s complement, 32-bit representations of integers.
2. Performs right shifts arithmetically.
3. Has unpredictable behavior when shifting an integer by more
than the word size.
/*
* evenBits - return word with all even-numbered bits set to 1
* Legal ops: ! ~ & ^ | + << >>
* Max ops: 8
* Rating: 2
*/
int evenBits(void) {
return ?;
}
The Attempt at a Solution
I have no idea! What I originally thought was that I would have to perform a shift by 31 (whether left or right, I don't know) so that all the numbers would be set to all 0's or 1's and work from there, but then I realized that the odd bits should probably remain the same. I guess I could create an int var, of -1 or something and go from there, but really I just don't know if that would accomplish anything. Any help would be greatly appreciated.
P.S does anyone know of some links that could give me a better understanding of all these bitwise and logical operations? Because I also have to do stuff like: if x <= y then return 1, else return 0 / implement the ! operator, using all of the legal operators except !/ x+y+z using only a single '+', and I would love to get a better understanding why/how to do this, instead of fumbling around for hours on end. Thanks!