简体   繁体   English

关注一段代码

[英]Concern regarding piece of code

I was looking at one of the open source project on github and I found following line of code in Java, 我正在查看github上的一个开源项目,我在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, 在这里我们知道1 << 11只不过是2048,所以我可以通过给出长度= 2048来直接初始化数组,如下所示,

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

then why it is written like 1 << 11 instead of 2048 directly. 那为什么它直接写成1 << 11而不是2048。

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. 使用逐位操作的原因是要明确这是2的幂。我看到人们混淆常数。 eg 8096 which is a combination of 8192 and 4096. 例如8096,它是8192和4096的组合。

What I prefer to do is use << 10 or << 20 for KB and MB. 我更喜欢做的是使用<< 10<< 20表示KB和MB。 eg 2 << 10 for 2 KB 例如2 << 10 for 2 KB

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM