Golang读者们:为什么要使用位运算符<<来写入int64数字?

huangapple go评论76阅读模式
英文:

Golang readers: Why writing int64 numbers using bitwise operator <<

问题

我在处理Go读取器时遇到了以下代码,用于在通过多部分上传(例如在Postman中)发送文件时限制从远程客户端读取的字节数。

r.Body = http.MaxBytesReader(w, r.Body, 32<<20+1024)

如果我没弄错的话,上述表示的应该是33555456字节,或者33.555456 MB(32 * 2 ^ 20)+ 1024。这个数字是正确的吗?

我不明白的是:

  • 为什么作者要这样使用?为什么使用20而不是其他数字?
  • 为什么作者要使用+1024这样的表示法?为什么他不直接写成33 MB呢?
  • 直接将33555456写成int64类型是否可以?
英文:

I have come across the following code when dealing with Go readers to limit the number of bytes read from a remote client when sending a file through multipart upload (e.g. in Postman).

r.Body = http.MaxBytesReader(w, r.Body, 32&lt;&lt;20+1024)

If I am not mistaken, the above notation should represent 33555456 bytes, or 33.555456 MB (32 * 2 ^ 20) + 1024. Or is this number not correct?

What I don't understand is:

  • why did the author use it like this? Why using 20 and not some other number?
  • why the author used the notation +1024 at all? Why didn't he write 33 MB instead?
  • would it be OK to write 33555456 directly as int64?

答案1

得分: 2

如果我没记错的话,上面的表示应该是33555456字节,或者33.555456 MB(32 * 2 ^ 20)+ 1024。这个数字是正确的吗?

正确。你可以自己简单地验证一下。

fmt.Println(32<<20+1024)

为什么他没有写成33 MB呢?

因为这个数字不是33 MB。33 * 1024 * 1024 = 34603008

直接将33555456写成int64类型可以吗?

当然可以。在编译过程中,它很可能被转换为int64类型。一旦你理解了32、20和1024之间的逻辑,这种表示法可能更容易阅读。

阅读的便利性是我几乎总是(当不使用Ruby时)将常量写成"50 MB"形式的50 * 1024 * 1024,将"30 days"写成30 * 86400等的原因。

英文:

> If I am not mistaken, the above notation should represent 33555456 bytes, or 33.555456 MB (32 * 2 ^ 20) + 1024. Or is this number not correct?

Correct. You can trivially check it yourself.

fmt.Println(32&lt;&lt;20+1024)

> Why didn't he write 33 MB instead?

Because this number is not 33 MB. 33 * 1024 * 1024 = 34603008

> would it be OK to write 33555456 directly as int64?

Naturally. That's what it likely is reduced to during compilation anyway. This notation is likely easier to read, once you figure out the logic behind 32, 20 and 1024.

Ease of reading is why I almost always (when not using ruby) write constants like "50 MB" as 50 * 1024 * 1024 and "30 days" as 30 * 86400, etc.

huangapple
  • 本文由 发表于 2021年10月28日 20:33:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/69754183.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定