Go: Large Numbers

Go: Large Numbers

Create a large number in Go using the shift operator.

Β·

2 min read

Sometimes you need to define large numeric constants. Instead of typing a large number you can use the shift operator to generate a large constant.

package main

import "fmt"

const (
    // Create a huge number 
    Big = 1 << 100

    // Shift bit right again
    Small = Big >> 99
)

func needInt(x int) int {
    return x
}

func needFloat(x float64) float64 {
    return x
}

func main() {
    fmt.Println(needInt(Small))
    fmt.Println(needFloat(Small))
    fmt.Println(needFloat(Big))
}

Try it: https://go.dev/play/p/NXsYbn_OsZm

Notes:


In the previous example, we have factored out the const keyword to define two constants with "=" and expression. The constant Big and Small are public but is of no use since this package is called "main" and is not imported anywhere. So you could have used lowercase.

This code demonstrates also the difference between int and float64 types in Go.

The constants Big and Small are defined:

Big = 1 << 100 creates a huge integer by left shifting 1 by 100 bits.

Small is created by right shifting Big by 99 bits, so it's a smaller integer.

The needInt() and needFloat() functions accept an int and float64 respectively.

In main():

  • needInt(Small) works because Small is an int.

  • needFloat(Small) works because Small, though an int, can be implicitly converted to float64.

  • needFloat(Big) fails to compile because Big is too large to fit into a float64.

So this code shows that:

  • Integers have a limited range, while float64 can represent a wider range of values.

  • Implicit type conversion from int to float64 is allowed, but not the reverse.


Disclaim: The notes are created with ChatGPT


Have fun. Life is short! πŸ––πŸΌπŸ€

Β