Wednesday, February 13, 2008
Some Quizzes on Bits, Bytes, etc.
- Given a byte, how would you turn the nth bit on ?
- Given a byte, how would you turn the nth bit off ?
- Given a long, how would you return 8 bytes (in big-endian order) containing the two's-complement binary representation of the long ?
- Given 8 bytes (in big-endian order) containing the two's-complement binary representation of a long, how would you return the long ?
- Given a UUID, how would you return a BigInteger representing the numeric value of the underlying 128-bit ?
(Don't peek if you want to give it a try!)
- Given a byte, how would you turn the nth bit on ?
public static byte setBitOn(byte b, int n) {
return (byte)(b | 1 << n);
} - Given a byte, how would you turn the nth bit off ?
public static byte setBitOff(byte b, int n) {
int mask = 0xFF - (1 << n);
return (byte)(b & mask);
} - Given a long, how would you return 8 bytes (in big-endian order) containing the two's-complement binary representation of the long ?
public static byte[] longTobytes(long val) {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.putLong(val);
return bb.array();
} - Given 8 bytes (in big-endian order) containing the two's-complement binary representation of a long, how would you return the long ?
public static long bytesTolong(byte[] ba) {
ByteBuffer bb = ByteBuffer.allocate(8);
bb.put(ba);
bb.flip();
return bb.getLong();
} - Given a UUID, how would you return a BigInteger representing the numeric value of the underlying 128-bit ?
public static BigInteger toBigInteger(UUID uuid) {
long msb = uuid.getMostSignificantBits();
long lsb = uuid.getLeastSignificantBits();
ByteBuffer bb = ByteBuffer.allocate(16);
bb.putLong(msb).putLong(lsb);
return new BigInteger(bb.array());
}