How to copy bits from one variable to another?

空扰寡人 提交于 2019-12-09 13:07:30

问题


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.


回答1:


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?




回答2:


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);



回答3:


Try:

v1 = (v2 & 0x0F) | (v1 & 0xF0);



回答4:


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


来源:https://stackoverflow.com/questions/14391707/how-to-copy-bits-from-one-variable-to-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!