I was reading this book entitled, Cracking the Coding Interview by Laakman. There is this part where she (the author p.g. 202) did:
byte[] bitfield = new byte [0xFFFFFFF/8];//there are 7 F's
She was allocating 4 billion bits. However, isn’t 0xFFFFFFF = 2^28-1? Thus, she has only allocated a byte array of 2^28-1/8 bytes, which is not remotely close to 4 billion bits. It is only 2^28-1 bits. My question is- is she wrong or am I doing something wrong? How do we allocate 4 billion bits? I have tried:
byte[] bitfield = new byte[0xfffffff *2];
Although the above causes the jvm to run out of heap space.
While we are at it, what is the best was to express hex values? e.g. 0xffffffff or 0xFFFFFFFF?
It’s not clear to me why you’re multiplying by 2. It’s simplest to just take the hex representation of (4 billion / 8) – where by “4 billion” we really mean 0x100000000.
So use 0x100000000 / 8, i.e. 0x2000000:
That should be fine if you’ve given your JVM enough memory on startup, e.g. with -Xmx900M.
Sample code:
Run by default:
Run with a bit more space: