Archive for January 2008

Taking the Steve Yegge Challenge (Part 1: Bits and Bytes)

A few months ago I read Steve Yegge’s old post about phone screen tips, which included five categories that at a minimum should be covered during a phone screen. I found that I wasn’t as up to snuff as I thought I was in a couple of those categories, including “Bits and Bytes”. I took this as a challenge.

In particular I discovered I couldn’t even name the size in memory of each of the Java primitives. About a month ago I looked them all up, as I was preparing to interview for a job at Terracotta. The sad thing is, I’ve already forgotten them all again. So I am hoping now, once and for all, to burn them into my brain.

Java primitives:

primitive size (bits) min value max value comments
byte 8 -27 = -128 27-1 = 127 signed 2's complement
short 16 -215 = -32768 215-1 = 32767 signed 2's complement
int 32 -231 = -2,147,483,648 231-1 = 2,147,483,647 signed 2's complement
long 64 -263 = -9,223,372,036,854,775,808 263-1 = 9,223,372,036,854,775,807 signed 2's complement
float 32     32-bit IEEE 754 floating point
double 64     64-bit IEEE 754 floating point
char 16 '\u0000' (or 0) '\uffff' (or 65,535) Unicode
boolean       size isn't precisely defined in JLS

Java bitwise and bit shift operators (legal on Java integral types)

operator explanation comment
~ bitwise complement inverts a bit pattern
<< signed left shift keeps sign (high bit) of first operand
>> signed right shift keeps sign (high bit) of first operand
>>> unsigned right shift shifts a zero into high (leftmost) bit
& bitwise and see a clever real-world use of this
| bitwise or  
^ bitwise exclusive or  

Notes on 2’s complement:

  • high (leftmost) bit indicates sign (0 indicates positive, 1 indicates negative)
  • largest value for n bits is 2(n-1)-1, smallest value is -2(n-1)
  • processors can treat (add) all numbers uniformly (no need to check for sign and/or subtract)
  • To negate a two’s-complement number, invert all the bits (bitwise NOT) then add 1 to the result.
  • More conceptually, 2’s compliment of positive number obtained by subtracting that from 2n. For example, for 8 bits, “-3″ is gotten by subtracting “3″ (00000011) from 28 (100000000) to get (11111101).
  • One interesting side effect of 2’s complement is that the smallest negative number is a weird number - it violates the aforementioned algorithm to flip the bit, which all other numbers adhere to. This leads to an exciting “feature” of Math.abs(), where it’s possible for that method to return a negative number. For example, using the smallest negative int, Math.abs(-2147483648) returns -2147483648!