如何将位从一个变量复制到另一个? [英] How to copy bits from one variable to another?

查看:141
本文介绍了如何将位从一个变量复制到另一个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 int 变量 v1

  1100 1010 

c> int v2 :

  1001 1110 
/ pre>

我需要将 v2 的最后四位复制到 v1 ,以便结果是:

  1100 1110 
^ ^位v2
|
|前4位v1

我如何在C或C ++中做这件事?我读了几篇关于逐位操作的文章,但是我找不到任何具体的信息。

解决方案

  v1 =(v1&〜0xf)| (v2& 0xf); 

您从阅读的文章中发现了不明白的地方吗?


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?

这篇关于如何将位从一个变量复制到另一个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆