![]() |
The Java Developers Almanac 1.4 |
|
e129. Performing Bitwise Operations with BigIntegerABigInteger object is immutable. For a mutable object that supports
bitwise operations, see e363 Performing Bitwise Operations on a Bit Vector.
// Create via an array of bytes in twos-complement form.
// The byte-ordering is big-endian which means the most significant bit is in element 0.
// A negative value
byte[] bytes = new byte[]{(byte)0xFF, 0x00, 0x00}; // -65536
// A positive value
bytes = new byte[]{0x1, 0x00, 0x00}; // 65536
BigInteger bi = new BigInteger(bytes);
// Get the value of a bit
boolean b = bi.testBit(3); // 0
b = bi.testBit(16); // 1
// Set a bit
bi = bi.setBit(3);
// Clear a bit
bi = bi.clearBit(3);
// Flip a bit
bi = bi.flipBit(3);
// Shift the bits
bi = bi.shiftLeft(3);
bi = bi.shiftRight(1);
// Other bitwise operations
bi = bi.xor(bi);
bi = bi.and(bi);
bi = bi.not();
bi = bi.or(bi);
bi = bi.andNot(bi);
// Retrieve the current bits in a byte array in twos-complement form.
// The byte-ordering is big-endian which means the most significant bit is in element 0.
bytes = bi.toByteArray();
e127. Operating with Big Decimal Values e128. Setting the Decimal Place of a Big Decimal Value e130. Parsing and Formatting a Big Integer into Binary, Octal, and Hexadecimal e131. Parsing and Formatting a Byte Array into Binary, Octal, and Hexadecimal © 2002 Addison-Wesley. |