Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an int64 to int in Go?

Tags:

int

go

int64

In Go, what is the best strategy for converting int64 to int? I am having difficulty comparing the two

package main   import (     "math"     "strings"     "strconv" )  type largestPrimeFactor struct {     N      int     Result int }  func main() {     base := largestPrimeFactor{N:13195}     max := math.Sqrt(float64(base.N))      maxStr := strconv.FormatFloat(max, 'E', 'G', 64)     maxShift := strings.Split(maxStr, ".")[0]     maxInt, err := strconv.ParseInt(maxShift, 10, 64)      if (err != nil) {         panic(err)     } 

on this next line

    for a := 2; a < maxInt; a++ {         if isPrime(a) {             if base.N % a == 0 {                 base.Result = a             }         }     }      println(base) }  func isPrime(n int) bool {     flag := false      max := math.Sqrt(float64(n))      maxStr := strconv.FormatFloat(max, 'E', 'G', 64)     maxShift := strings.Split(maxStr, ".")[0]     maxInt, err := strconv.ParseInt(maxShift, 10, 64)      if (err != nil) {         panic(err)     }      for a := 2; a < maxInt; a++ {         if (n % a == 0) {             flag := true         }     }     return flag } 
like image 604
pward Avatar asked Aug 03 '16 17:08

pward


People also ask

Is int Int64 in Golang?

int is one of the available numeric data types in Go used to store signed integers. int64 is a version of int that only stores signed numeric values composed of up to 64 bits.

How do you cast to int in go?

In order to convert string to integer type in Golang, you can use the following methods. You can use the strconv package's Atoi() function to convert the string into an integer value. Atoi stands for ASCII to integer. The Atoi() function returns two values: the result of the conversion, and the error (if any).

How do you convert types of go?

Typecasting in Golang is a way to convert the variable from one data type to another data type. For instance, if you want to save the long value into a simple integer, you can typecast long to int. You can convert the values from one type to another using the cast operator.

What is the difference between Int32 and Int64?

Int32 is used to represents 32-bit signed integers . Int64 is used to represents 64-bit signed integers.


1 Answers

You convert them with a type "conversion"

var a int var b int64 int64(a) < b 

When comparing values, you always want to convert the smaller type to the larger. Converting the other way will possibly truncate the value:

var x int32 = 0 var y int64 = math.MaxInt32 + 1 // y == 2147483648 if x < int32(y) { // this evaluates to false, because int32(y) is -2147483648 

Or in your case to convert the maxInt int64 value to an int, you could use

for a := 2; a < int(maxInt); a++ { 

which would fail to execute correctly if maxInt overflows the max value of the int type on your system.

like image 106
JimB Avatar answered Oct 04 '22 19:10

JimB