如何设置,清除和切换单个位? [英] How do you set, clear, and toggle a single bit?

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

问题描述

如何设置,清除和切换位?

How do you set, clear, and toggle a bit?

推荐答案

设置位

使用按位或运算符(|)设置一个位.

number |= 1UL << n;

这将设置number的第n位.如果要设置1 st位,将n设置为零;如果要设置n th位,将n-1设置为n-1.

That will set the nth bit of number. n should be zero, if you want to set the 1st bit and so on upto n-1, if you want to set the nth bit.

如果number宽于unsigned long,请使用1ULL;否则,请使用1ULL.直到评估了1UL << n之后,1UL << n的提升才发生,在这种情况下,未定义的行为会移动超过long的宽度.其余所有示例都一样.

Use 1ULL if number is wider than unsigned long; promotion of 1UL << n doesn't happen until after evaluating 1UL << n where it's undefined behaviour to shift by more than the width of a long. The same applies to all the rest of the examples.

使用按位AND运算符(&)清除一位.

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

number &= ~(1UL << n);

这将清除number的第n位.您必须使用按位NOT运算符(~)反转位字符串,然后将其取反.

That will clear the nth bit of number. 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 ^= 1UL << n;

这将切换number的第n位.

您没有要求这样做,但我也可以添加它.

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

要检查一下,将数字n右移,然后按位与它相符:

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

bit = (number >> n) & 1U;

这会将number的第n位的值放入变量bit.

That will put the value of the nth bit of number into the variable bit.

使用2的补码C ++实现,可以将第n位设置为10:

Setting the nth bit to either 1 or 0 can be achieved with the following on a 2's complement C++ implementation:

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

如果x1,则

n将被置位,如果x0,则清零.如果x具有其他值,则会产生垃圾. x = !!x会将其布尔值设置为0或1.

Bit n will be set if x is 1, and cleared if x is 0. If x has some other value, you get garbage. x = !!x will booleanize it to 0 or 1.

要使其独立于2的补码取反行为(其中-1设置了所有位,与1的补码或符号/幅值C ++实现不同),请使用无符号取反.

To make this independent of 2's complement negation behaviour (where -1 has all bits set, unlike on a 1's complement or sign/magnitude C++ implementation), use unsigned negation.

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

unsigned long newbit = !!x;    // Also booleanize to force 0 or 1
number ^= (-newbit ^ number) & (1UL << n);

使用无符号类型进行可移植位操作通常是一个好主意.

It's generally a good idea to use unsigned types for portable bit manipulation.

number = (number & ~(1UL << n)) | (x << n);

(number & ~(1UL << n))将清除第n位,而(x << n)将第n位设置为x.

(number & ~(1UL << n)) will clear the nth bit and (x << n) will set the nth bit to x.

通常不要复制/粘贴代码也是一个好主意,因此很多人使用预处理器宏(例如社区Wiki进一步回答)或某种封装.

It's also generally a good idea to not to copy/paste code in general and so many people use preprocessor macros (like the community wiki answer further down) or some sort of encapsulation.

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

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