Reputation: 25
I have a decimal number that I need to manipulate 4 bits in with a given shift. For example, if the number is 208, or 11010000 binary, and I want to change 4 bits to 1101 with a shift of 2. The new number will be 244. When the change was: 11110100. Here's my code:
void change_bit(int num, int bit, int shift)
{
num = (num & (0xfffffff0<<shift)) | (bit << shift);
printf("%d\n", num);
}
The shifting of 0xfffffff0 just adds '0' to the left size. How can I fix it?
Upvotes: 1
Views: 739
Reputation: 67476
It is easier if you split complex expressions into smaller bits. It does not affect the efficiency of the code but it will be much easier for you read and understand.
unsigned change_bit(unsigned num, unsigned bit, int shift)
{
unsigned mask = ((1U << 4) - 1) << shift; // mask to reset the bits at the position
num &= ~mask; //reset the bits
num |= bit << shift; //set the bits
return num;
}
or more generally
unsigned change_bit(unsigned num, unsigned newval, int shift, int numbits)
{
unsigned mask = ((1 << numbits) - 1) << shift;
num &= ~mask;
num |= newval << shift;
return num;
}
and some test code:
void print(unsigned val)
{
for(unsigned x = 1U << 31; x ; x >>= 1)
{
printf("%d", !!(val & x));
}
printf("\n");
}
int main(void)
{
print(208);
print(change_bit(208, 0b1101, 2));
printf("%d\n", change_bit(208, 0b1101, 2));
}
You should also add some parameters checks.
Upvotes: 4