bitwise operators(info)

C

Ceriousmall

Guys I wanna say thanks for all the help and pointers with this
bitwise exercise.
This is the code I've come up with.......

unsigned setbits(unsigned x, int p, int n, unsigned y)
{
unsigned mask = ~(~0 << n);

return x & ~(mask << (p+1-n)) | ((y & mask) << (p+1-n));
}
 
B

Ben Bacarisse

Ceriousmall said:
Guys I wanna say thanks for all the help and pointers with this
bitwise exercise.

You missed a bit of advice...
This is the code I've come up with.......

unsigned setbits(unsigned x, int p, int n, unsigned y)
{
unsigned mask = ~(~0 << n);

~0 has (on all the machines you are likely to come across[1]) a value
less than zero. Shifting a negative value left is undefined even though
it may work. It's better, therefore, to write:

unsigned mask = ~(~0u << n);

and there are other ways too: ~(-1u << n) and ~(UINT_MAX << n) for
example.
return x & ~(mask << (p+1-n)) | ((y & mask) << (p+1-n));
}

Since the exercise did not specify how the bits are numbered, you don't
have to use such a complex shift expression. I'd argue that

return x & ~(mask << p) | ((y & mask) << p);

meets the spec. perfectly well but there's nothing wrong with your
way. Well done!

[1] I don't want to get into an argument as to whether -0 is a
"nonnegative value" for the purposes of 6.5.7p4.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,787
Messages
2,569,627
Members
45,328
Latest member
66Teonna9

Latest Threads

Top