2

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.

4
  • The code pasted here didn't even compile for me. Two errors and two warnings. After fixing those, I got 01234567. Commented Feb 15, 2017 at 20:34
  • Decimal 17512807 will be hexadecimal 010B3967. Commented Feb 15, 2017 at 20:36
  • Your code can invoke undefined behaviour. int is 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!) Commented Feb 15, 2017 at 20:49
  • @Olaf I had not noticed that int value = 17512807u; does not change int value to unsigned type. Commented Feb 15, 2017 at 20:57

3 Answers 3

1
int mask = ((1 << (L - R + 1)) - 1) << R; 
Sign up to request clarification or add additional context in comments.

Comments

0

Your expressions to compute mask are incorrect. You changed the parentheses in the second expression but both are incorrect, and do not even compile:

int mask = ((1 << (L - R + 1) - 1) << R; ... mask = ((1 << (L - R + 1) - 1 << R); 

should be written:

mask = ((1UL << (L - R + 1)) - 1) << R; 

Comments

0

Looks like what you are asked to do is use the bit fields. For example, given the type

struct bits{ int a:5; unsigned short b:3; unsigned char c:2; bool d:1; }; 

The above struct will have 4 members, each of specific bit length.

If you union that struct with an int you get a "dual-view" of the bits. As a list of fields or as a single integer:

union U{ struct bits fields; int i; }; 

Now the code like

U u; u.i = 0; u.fields.b = true; 

becomes valid and gives you access to either the whole number or individual bit fields.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.