Common Bit Tasks
1) If you XOR a bit with its own negated value, you will always get 1. Therefore thesolution to a ^ (~a) will be the sequence of 1s.
consider a is of data-type byte.
example:
a = 00000001
~a = 11111110
Now a ^ (~a) = 11111111
2) An operation like x & (~0 << n) clears the n rightmost bits of x. The value ~o is the sequences of 1s, so by shifting it by n, we have a bunch of ones followed by n zeros. By doing AND we clear the the rightmost n digits
of x.
3) Bit Facts and Tricks:
x ^ 0′s = x x & 0′s = 0 x | 0′s = x
x ^ 1′s = ~x x & 1′s = x x | 1′s = 1′s
x ^ x = 0 x & x = x x | x = x
4) Get Bit :
If I want to get the bit at i-th position, this method shifts1 over by i bits , creating a value and performing an
AND operation with the numbernum. If the resultant value is zero, that bit is unset else, that bit is set.
1
2
3
|
boolean
int num, int i) { return ((num & ( 1 << i)) != 0 ); } |
5) Set Bit:
If I want to set the bit at i-th position, this method shifts1 over by i bits , creating a value and performing an
OR operation with the numbernum.
1
2
3
|
public setBit( int num, int i) { return num | ( 1 << i); } |
6) Clear Bit:
This method operates in reverse way as the setBit method works. To clear the
i-th bit we first negate the result obtained from 1 << i and perform AND operation with the numbernum.
1
2
3
4
|
public clearBit( int num, int i) { int mask = ~( 1 << i); return num & mask; } |
7) Clear all the MSB through i (inclusive) 高位到低位清零(包括低位)
This method is meant for clearing all the MSB’s (Most Significant Bits) through i (inclusive) we do:
1
2
3
4
|
public clearBitsMSBThrough( int num, int i) { int mask = ( 1 << (i + 1 ) ) - 1 ; return num & mask; } |
8) Clear all the bits from i through o(inclusive) 低位到0位清零 (包括低位)
This method is meant for clearing all the bits from i through 0 from the number num:
1
2
3
4
|
public clearBitsIthrough0( int num, int i) { int mask = ~( 1 << (i + 1 )) - 1 ; return num & mask; } |
最新文章
- python开发编译器
- UIApplication和OpenUrl的基于使用方法
- 用ABBYY提取文本和表格的方法
- 安装windows git客户端
- 设计 REST 风格的 MVC 框架
- Ngui _CD技能特效
- 阿里巴巴2014研发project师实习生面试经历
- Request中的方法调用
- bootstrap_下拉菜单+头部
- HDU 4333 [SAM WRONG!!!]
- sql with as 用法-Z
- iOS监听模式系列之NSNotificationCenter的简单使用
- [TCP/IP] 计算机网络性能指标
- SAP MM盘点流程里如何处理事务代码MI11 Recount过的盘点凭证?
- Go语言基础(一)
- redis搭建主从复用-读写分离
- DWR第二篇之逆向Ajax
- Cocos Creator学习笔记
- webstorm11.0下载地址和webstorm11.0破解程序patcher.exe下载使用方法说明 前端IDE工具的利器
- Golang 笔记 5 go语句