How to copy bits from one variable to another?

邮差的信 提交于 2019-12-03 15:13:37

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

Try:

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

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