更改位C中的诠释? [英] Changing bits in an int in C?

查看:121
本文介绍了更改位C中的诠释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个16位的数字。说,对于它的变量名是位。我想要让这个位[2:0] = 001,100,万和,在不改变任何东西。我不知道如何做到这一点,因为所有我能想到的是或运算位我想成为一个1 1,但我不知道如何让他们为0。如果有人清除其他位有建议,我倒是AP preciate它。谢谢!

So I have a 16 bit number. Say that the variable name for it is Bits. I want to make it so that Bits[2:0] = 001, 100, and 000, without changing anything else. I'm not sure how to do it, because all I can think of is ORing the bit I want to be a 1 with 1, but I'm not sure how to clear the other bits so that they're 0. If anyone has advice, I'd appreciate it. Thanks!

推荐答案

要清除某些位,&安培; 与位的倒数被清除。然后你可以 | 在您需要的位

To clear certain bits, & with the inverse of the bits to be cleared. Then you can | in the bits you want.

在这种情况下,你要零出低三位(十进制111 二进制或 7 ),所以我们&放大器; 〜7 来清除这些位

In this case, you want to zero out the lower three bits (111 in binary or 7 in decimal), so we & with ~7 to clear those bits.

Bits = (Bits & ~7) | 1; // set lower three bits of Bits to 001

这篇关于更改位C中的诠释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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