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

This topic is 4321 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## 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 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 on other sites
Even Simpler ...

just do this :

int value = (17 <<5);

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

Sneftel is right.

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

##### Share on other sites
in = 17;
var = something you want to change

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

should work. I haven't tried it though.

##### Share on other sites
Quote:
 Original post by Necatorin = 17;var = something you want to changevar = (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 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 on other sites
Quote:

You need to decrease with 1 before you complement it.

1. 1
2. 2
3. 3
4. 4
frob
15
5. 5

• 16
• 12
• 20
• 12
• 18
• ### Forum Statistics

• Total Topics
632160
• Total Posts
3004500

×