Let's say I have this int
variable v1
:
1100 1010
And this variable int v2
:
1001 1110
I need to copy the last four bits from v2
to the last four bits of v1
so that the result is:
1100 1110
^ ^ last four bits of v2
|
| first four bits of v1
How would I got about doing this in C or C++? I read a few articles about bitwise operations but I couldn't find any information specifically about this.
Bitwise operations were the right things to look for.
v1 = (v1 & ~0xf) | (v2 & 0xf);
Is there something specific you didn't understand from the articles you read?
How about
v1 = (v1 & 0xf0) | (v2 & 0xf);
If the value of "v1" has more bits, you'd want to use a bigger mask:
v1 = (v1 & 0xfffffff0) | (v2 & 0xf);
The most readable way to write it, in my opinion:
v1 &= ~0x0F; // clear least sig. nibble of v1
v1 |= v2 & 0x0F; // copy least sig. nibble of v2 into v1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With