Of the puzzles given, solve as many as you can. Each must be solved in its own…
- User
Of the puzzles given, solve as many as you can. Each must be solved in its own well-formed function definition to count for credit. You may not use casting from one type to another in your solutions, and doing so will result in a 0 on that puzzle. You may only use 1 byte, hexadecimal constants, and using anything larger will result in a 0 on that puzzle.
You may only use !, ~, |, &, ^, +, <<, and >>. You may not use control structures such as if, then, else, for, while, do-while loops, switch, etc.
Each puzzle solved is worth at most 20 points if it is solved within the restrictions listed in the above paragraph. If the above rules are not followed, that puzzle is worth at most 10 points. Partial credit is available for partial solutions at my discretion.
The maximum score available is 200, but the value of the assignment as a whole is 150. Not every puzzle must be solved in order to get full points on this homework. (Hint: this is an opportunity to make up for lost points on reading quizzes!)
int logicalShift(int x, int n);
// Shift right logical, even though int is a signed variable. Use a maximum of 20 operations.
int bitParity(int x);
// returns 1 if x contains an odd number of 0's. Use a maximum of 20 operations.
- Assistant
Sure! Here are the function definitions, within your specified constraints, to solve the given puzzles.
Puzzle 1: Logical Shift
To implement the logical right shift on an integer
xbynpositions, we have to ensure that the shift is not an arithmetic shift. Arithmetic shifts propagate the sign bit, while logical shifts do not. We can create a mask to clear the shifted-in bits.cint logicalShift(int x, int n) { // Step 1: Perform an arithmetic right shift int shifted = x >> n; // Step 2: Create a mask with 0s for sign-extended bits and 1s for the rest int mask = ~((1 << 8 - n) << n); // Step 3: Use the mask to clear the propagated sign bits return shifted & mask; }Puzzle 2: Bit Parity