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

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

问题描述

你如何设置、清除和稍微切换?

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

推荐答案

设置一点

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

number |= 1UL << n;

这将设置 numbernth 位.n 应该为零,如果你想设置 1st 位等等直到 n-1,如果你想设置 nth 位.

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.

如果numberunsigned long 更宽,则使用1ULL1UL <<<;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.

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

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

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

这将清除 numbern 位.您必须使用按位非运算符 (~) 反转位字符串,然后将其与.

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;

这将切换numbern位.

你没有要求这个,但我不妨加上它.

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.

n 位设置为 10 可以通过以下 2 的补码 C++ 实现来实现:

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

nx1时置位,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) 会将 nth 位设置为 x.

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

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

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天全站免登陆