Sign in to follow this  
Hybrid666

C++: replacing a number of bits in a 32 bit value

Recommended Posts

Hi, im interested in finding out the best way to replace a number of bits within a 32 bit value, in a way that could allow the middle 7 bits to be written to with a value, if i wanted. its probably a simple question but my knowledge of bitwise operators is a bit limited :) quick example for clairty: i pass the number 17 to a function, and want that value to be written to bits 5-9 of my 32 bit value (5 bits is enough to store 17), but not affecting the data in any other part of the 32 bit value, how do i do it? :) thanks in advance! Rich

Share this post


Link to post
Share on other sites
Zero out the bit range in the target by ANDing the target with the complement of the bitrange (so for replacing the middle few bits, it'd be something like 111111110000111111), then OR it with the replacement bit pattern (shifted left to be in the correct place).

Share this post


Link to post
Share on other sites
Even Simpler ...

just do this :

int value = (17 <<5);

[edit]
oups ... I didn't saw the "without altering the rest stuff".

Sneftel is right.

int value = ((value & 0xFC1F) | (17 << 5));

Share this post


Link to post
Share on other sites
Quote:
Original post by Necator
in = 17;
var = something you want to change

var = (var & ~(31 << 5)) | (in << 5);

should work. I haven't tried it though.


That of course assumes that in is always in range, if it isn't we will overwrite other data.

The more general (the values in [] are the values in your example):
in_bits = the number of bits in may maximally take = [5]
start = the number of bits before in = [5]
in = what you want to write = [17]
mask = (1<<in_bits)-1 = [31==111112] EDIT: As Necator pointed out this was flawed, is now fixed
(in &= mask) (if needed, make sure in isn't too large, you could also signal an error) = [17]
var = something you want to change

var = (var & ~(mask << start)) | (in << start);

That should work, of course in real code there are also other kinds of overflows you should consider, for example can in << start be in an int?

[Edited by - CTar on October 20, 2006 3:30:16 AM]

Share this post


Link to post
Share on other sites
wow quick replies!

thanks guys, i wasn't considering that it was a 2 step process - first clear the necessary bits, then set them :)

i'll try out your suggestions! :)

Rich

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this