Tutorial by Examples

It is common for memory performance to compress multiple values into a single primitive value. This may be useful to pass various information into a single variable. For example, one can pack 3 bytes - such as color code in RGB - into an single int. Packing the values // Raw bytes as input byte...
Assuming we want to modify bit n of an integer primitive, i (byte, short, char, int, or long): (i & 1 << n) != 0 // checks bit 'n' i |= 1 << n; // sets bit 'n' to 1 i &= ~(1 << n); // sets bit 'n' to 0 i ^= 1 << n; // toggles the value of bit 'n' Us...
For expressing the power of 2 (2^n) of integers, one may use a bitshift operation that allows to explicitly specify the n. The syntax is basically: int pow2 = 1<<n; Examples: int twoExp4 = 1<<4; //2^4 int twoExp5 = 1<<5; //2^5 int twoExp6 = 1<<6; //2^6 ... int twoEx...
If an integer x is a power of 2, only one bit is set, whereas x-1 has all bits set after that. For example: 4 is 100 and 3 is 011 as binary number, which satisfies the aforementioned condition. Zero is not a power of 2 and has to be checked explicitly. boolean isPowerOfTwo(int x) { return (x ...
Since 1.7 there's a java.util.BitSet class that provides simple and user-friendly bit storage and manipulation interface: final BitSet bitSet = new BitSet(8); // by default all bits are unset IntStream.range(0, 8).filter(i -> i % 2 == 0).forEach(bitSet::set); // {0, 2, 4, 6} bitSet.set(3);...
In Java, all number primitives are signed. For example, an int always represent values from [-2^31 - 1, 2^31], keeping the first bit to sign the value - 1 for negative value, 0 for positive. Basic shift operators >> and << are signed operators. They will conserve the sign of the value. ...

Page 1 of 1