Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concern regarding piece of code

Tags:

java

I was looking at one of the open source project on github and I found following line of code in Java,

static byte[] byteArray = new byte[1 << 11];

here we know that 1 << 11 is nothing but 2048, so I can directly initialize array by giving its length = 2048 as follow,

static byte[] byteArray = new byte[2048];

then why it is written like 1 << 11 instead of 2048 directly.

like image 247
MJP Avatar asked Feb 05 '17 11:02

MJP


1 Answers

The reason to use a bit wise operation is to make it clear this is a power of 2. I have seen people confuse the constant. e.g. 8096 which is a combination of 8192 and 4096.

What I prefer to do is use << 10 or << 20 for KB and MB. e.g. 2 << 10 for 2 KB

like image 168
Peter Lawrey Avatar answered Sep 21 '22 07:09

Peter Lawrey