How do I write an exponential constant like 2^7 in go

I am trying to loop through 127 to 227; 512 to 612… in other words 2^n to 2^n + 100 for various n.

package main

import (
    "fmt"
)

func main() {
    for i := int(2e7); i < int(2e7) + 100; i++ {
        fmt.Println(i, " - ", string(i), " - ", []byte(string(i)))
    }
}

However, I get a weird output :

go run main.go
20000000  -  �  -  [239 191 189]
20000001  -  �  -  [239 191 189]
20000002  -  �  -  [239 191 189]
20000003  -  �  -  [239 191 189]
20000004  -  �  -  [239 191 189]
20000005  -  �  -  [239 191 189]
.
.
.

What’s the right way to write this piece of code?

2e7 is 2×107, not 27. This is the same in any other language that supports the “e” notation, as far as I know. You can write 27 as 1<<7, a one-bit shifted left seven times, or simply as 127… More generally you have https://golang.org/pkg/math/#Exp2 and similar functions in the same package.

7 Likes

Thanks!