Home > front end >  Golang readers: Why writing int64 numbers using bitwise operator <<
Golang readers: Why writing int64 numbers using bitwise operator <<

Time:10-29

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<<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?

CodePudding user response:

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<<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.

  •  Tags:  
  • go
  • Related