Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy bits from one variable to another?

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.

like image 723
laurent Avatar asked Jan 18 '13 02:01

laurent


3 Answers

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?

like image 146
Carl Norum Avatar answered Sep 28 '22 12:09

Carl Norum


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);
like image 40
Pointy Avatar answered Sep 28 '22 13:09

Pointy


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
like image 43
Lundin Avatar answered Sep 28 '22 13:09

Lundin