您如何设置,清除和C / C ++切换一个位? [英] How do you set, clear and toggle a single bit in C/C++?

查看:128
本文介绍了您如何设置,清除和C / C ++切换一个位?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何设置,清除和切换在C位/ C ++?

How do I set, clear and toggle a bit in C/C++?

推荐答案

使用位或操作符( | )设置位

Setting a bit

Use the bitwise OR operator (|) to set a bit.

number |= 1 << x;

这将设置位 X

使用按位与运算符(&安培; )来清除位

Use the bitwise AND operator (&) to clear a bit.

number &= ~(1 << x);

这将清除位 X 。您必须反转位串的按位NOT运算符(),那么,它

That will clear bit x. You must invert the bit string with the bitwise NOT operator (~), then AND it.

XOR运算符( ^ )可用于切换了一下。

The XOR operator (^) can be used to toggle a bit.

number ^= 1 << x;

这将触发位 X

您没有要求这一点,但我还不如将其添加。

You didn't ask for this but I might as well add it.

要查了一下,X移位数到右边,然后按位与它:

To check a bit, shift the number x to the right, then bitwise AND it:

bit = (number >> x) & 1;

这将会把位的值x 到变量

设置 N 个位为 1 0 可以用下面来实现:

Setting the nth bit to either 1 or 0 can be achieved with the following:

number ^= (-x ^ number) & (1 << n);

N 将会被设置 X 1 ,如果>清零x 0

Bit n will be set if x is 1, and cleared if x is 0.

这篇关于您如何设置,清除和C / C ++切换一个位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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