C bit 操作

C 位 操作

一、C bit 操作(C语言 二进制位 操作)

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

number |= 1 << x;

That will set bit x.

2.Toggling a bit

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

number ^= 1 << x;

That will toggle bit x.

3.Clearing a bit

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

number &= ~(1 << x);

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

4.Checking a bit

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

bit = (number >> x) & 1;

That will put the value of bit x into the variable bit

5.Changing the nth bit to x

二、C decimal 操作 (C语言 十进制位 操作)

1.Get a 位
和二进制的操作比较类似,其中的<<(二进制左移)在10进制里面相当于÷10。在10进制里面可以用循环来实现。

2.Set a 位

参考:


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

posted @ 2016-09-19 16:20  xiulug  阅读(1538)  评论(0编辑  收藏  举报