衫裤跑路 2008-09-07 00:42 采纳率: 50%
浏览 724
已采纳

你如何设置、清除和切换一个单位?

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

转载于:https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit

  • 写回答

26条回答 默认 最新

  • 七度&光 2008-09-07 00:50
    关注

    Setting a bit

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

    number |= 1UL << n;
    

    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.

    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.

    Clearing a bit

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

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

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

    Toggling a bit

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

    number ^= 1UL << n;
    

    That will toggle the nth bit of number.

    Checking a bit

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

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

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

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

    Changing the nth bit to x

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

    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.

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

    or

    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.

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(25条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?