您的位置:首页 > 编程语言 > Java开发

Bit manipulation

2014-07-22 01:46 267 查看
1. clear the n rightmost bits of x:  x & (~0 <<n)

2. getBit at i: boolean -> ((num & (1 << i)) != 0)

3. setBit at i: num |  (1  <<  i)

4. clear bit ati: num & ~(1 << i)

5. clearBitsMSBthroughI: num & ( (1 << i) - 1 )

6. clearBitsIthrough0: num & ~(1 << (i + 1) - 1)

7. Bit to String:

(1)

int x = 100;
System.out.println(Integer.toBinaryString(x));

(2)



Here no need to depend only on binary or any other format... one flexible built in function is available That prints whichever format you want in your program.. Integer.toString(int,representation);
Integer.toString(100,8) // prints 144 --octal representation

Integer.toString(100,2) // prints 1100100 --binary representation

Integer.toString(100,16) //prints 64 --Hex representation


8.representation

(1)

In Java edition 7, you can simply use binary numbers by declaring ints and preceding your numbers with 
0b
 or 
0B
:
int x=0b101;
int y=0b110;
int z=x+y;

System.out.println(x + "+" + y + "=" + z);
//5+6=11

/*
* If you want to output in binary format, use Integer.toBinaryString()
*/

System.out.println(Integer.toBinaryString(x) + "+" + Integer.toBinaryString(y)
+ "=" + Integer.toBinaryString(z));
//101+110=1011

(2)

What you are probably looking for is the 
BitSet
 class.

This class implements a vector of bits that grows as needed. Each component of the bit set has a boolean value. The bits of a BitSet are indexed by nonnegative integers. Individual indexed bits can be examined, set, or cleared. One BitSet may be used to modify
the contents of another BitSet through logical AND, logical inclusive OR, and logical exclusive OR operations.

By default, all bits in the set initially have the value false.

Every bit set has a current size, which is the number of bits of space currently in use by the bit set. Note that the size is related to the implementation of a bit set, so it may change with implementation. The length of a bit set relates to logical length
of a bit set and is defined independently of implementation.

Unless otherwise noted, passing a null parameter to any of the methods in a BitSet will result in a NullPointerException.

9.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java Bit