I'm trying to solve a question. It says,
Initialize a new variable to the value 17512807u.
Assume we number the bits as usual from 0 as least significant (on the right) to 31 (most significant, on the left). Update bits 18 through 21 with the integer value 8 and bits 10 through 14 with value 17 (decimal). Print the resulting value as an eight digit hexadecimal number to show all of the digits.
Here's the code I came up with:
#include <stdio.h> int main(){ int value = 17512807u; int L = 21; // starting left position int R = 18; // starting right position int mask = (1 << (L - R + 1) - 1) << R; int newField = (8 << R) & mask; // integer value 8, shifting to right int newValue = value & (~mask); // remove range of bits value = newField | newValue; // update range of bits L = 14; R = 10; mask = (1 << (L - R + 1) - 1) << R; newField = (17 << R) & mask; newValue = value & (~mask); value = newField | newValue; printf("%08x\n", value); } The answer I get is 012b7d67
However, I am told this is the incorrect answer. I do not know what the correct answer is.
17512807will be hexadecimal010B3967.intis not guaranteed to hold 32 bits. If you need a fixed bit-width, use fixed idth types. Oh, and it is in general better to use unsigned integer when shifting. signed integers can invoke undefined behaviour for certain values (not necessarily true for this example, just keep that in mind!)int value = 17512807u;does not changeint valuetounsignedtype.