0

I'm trying to solve a question that 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.

I understand what I'm required to do, and my code is working fine, but I'm told that my answer is incorrect.

#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); } 

Since I don't know the correct answer, and the only information I'm given is that my answer is wrong, I do not understand what I'm doing wrong.

4
  • Recently asked by OP here. Why are you still using int type for 17512807u value after being advised to use unsigned? Commented Feb 16, 2017 at 18:01
  • @WeatherVane I tried that, it doesn't change anything Commented Feb 16, 2017 at 18:22
  • So I guess you will continue to ignore that good advice from @Olaf? I do not understand why people ask questions and then carry on blindly. Commented Feb 16, 2017 at 19:30
  • The int in this case is guaranteed to be 32-bits. And as I said, I did change it to unsigned and it didn't make a difference. Commented Feb 17, 2017 at 4:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, I thought the only specified types available for bit field are _Bool, int, signed int, unsigned int. char c:2 may be a problem.
May want to post you answer at stackoverflow.com/q/42259429/2410359
Thank you, @chux. Updated the answer and cross-posted it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.