Simply Use the int() cast function

Answer from Ariel Monaco on Stack Overflow
🌐
Google Groups
groups.google.com › g › golang-nuts › c › 7yGYsdFTkWk
Convert int to int32 or int64
This should do it: myInt := (int)myInt64 Look at the topic conversions in the language spec. Note that this conversion will truncate the value if it doesn't fit into the int. On Sat, Apr 18, 2015 at 9:08 AM Brad Fitzpatrick <brad...@golang.org> wrote:
Discussions

How to convert [ ]int32 to [ ]int in Go - Stack Overflow
I have a slice of int32 that wants to convert to slice of int in Golang. I can convert it by iterating all values and changing the type then append it to a new int slice but I want to do it more More on stackoverflow.com
🌐 stackoverflow.com
Convert uint32 to int in Go - Stack Overflow
Simple type conversion, short: ... int = int(size). ... At first I thought a simple cast would work too. However, Go does not seem to allow this, the error message is not clear though. ... What error message? Would you care to post it? And simple conversion does work, see this example on the Go playground: play.golang.org/p/i... More on stackoverflow.com
🌐 stackoverflow.com
numeric - Go: convert big.Int to regular integer (int, int32, int64) - Stack Overflow
I assumed this would be a simple issue with abundant answers on the Internet. But that does not appear to be the case. I need to convert a Go big.Int into a regular integer (e.g., int, int32, or i... More on stackoverflow.com
🌐 stackoverflow.com
go - int vs int32 return value - Stack Overflow
I am running into an issue, which seems to be related to int32 vs int data type. My program is returning different values on different environments. For example, on go playground, I notice the va... More on stackoverflow.com
🌐 stackoverflow.com
🌐
gosamples
gosamples.dev › tutorials › convert int to string in go
🔢 Convert int to string in Go
July 23, 2021 - var number int = 12 // you can use any integer here: int32, int16, int8 str := strconv.FormatInt(int64(number), 10) fmt.Println(str) To convert int to string you can also use strconv.Itoa which is equivalent to strconv.FormatInt(int64(i), 10).
🌐
Stack Overflow
stackoverflow.com › questions › 74665476 › how-to-convert-int32-to-int-in-go
How to convert [ ]int32 to [ ]int in Go - Stack Overflow
However, keep in mind that with Go1.18 and up, using generics, you can implement this once for any combination of integers. For example: go.dev/play/p/FYq6TgWlULK ... Pointers vs. values in parameters and return values ... Pointers vs. values in parameters and return values ... Find the answer to your question by asking.
🌐
php.cn
m.php.cn › home › backend development › golang › how to convert int32 to int type in golang
How to convert int32 to int type in golang-Golang-php.cn
March 22, 2023 - The int32 and int types in Go language are both integer data types, but their representation ranges are different. In some projects, it is necessary to convert int32 to int type. The following is a detailed introduction to the method and precautions for converting int32 to int in Golang.
🌐
Stack Overflow
stackoverflow.com › questions › 77978215 › go-convert-big-int-to-regular-integer-int-int32-int64
numeric - Go: convert big.Int to regular integer (int, int32, int64) - Stack Overflow
I assumed this would be a simple issue with abundant answers on the Internet. But that does not appear to be the case. I need to convert a Go big.Int into a regular integer (e.g., int, int32, or i...
Find elsewhere
Top answer
1 of 1
24

The textbook you are looking for is

The Go Programming Language Specification

Numeric types

A numeric type represents sets of integer or floating-point values. The predeclared architecture-independent numeric types are:

uint32 set of all unsigned 32-bit integers (0 to 4294967295)
uint64 set of all unsigned 64-bit integers (0 to 18446744073709551615)

int32  set of all signed 32-bit integers (-2147483648 to 2147483647)
int64  set of all signed 64-bit integers (-9223372036854775808 to 9223372036854775807)

There is also a set of predeclared numeric types with implementation-specific sizes:

uint either 32 or 64 bits
int  same size as uint

Check the size of type int. On the Go Playground it's 4 bytes or 32 bits.

package main

import (
    "fmt"
    "runtime"
    "unsafe"
)

func main() {
    fmt.Println("arch", runtime.GOARCH)
    fmt.Println("int", unsafe.Sizeof(int(0)))
}

Playground: https://play.golang.org/p/2A6ODvhb1Dx

Output (Playground):

arch amd64p32
int 4

Run the program in your (LeetCode) environment. It's likely 8 bytes or 64 bits.

For example, in my environment,

Output (Local):

arch amd64
int 8

Here are some fixes to your code,

package main

import (
    "fmt"
    "runtime"
)

func main() {
    fmt.Println(runtime.GOARCH)
    fmt.Printf("%v\n", singleNumber([]int{-2, -2, 1, 1, -3, 1, -3, -3, -4, -2}))
}

func singleNumber(nums []int) int {
    sum := make([]int, 64)

    for _, v := range nums {
        for i := range sum {
            sum[i] += 1 & (v >> uint(i))
        }
    }

    res := 0
    for k, v := range sum {
        if (v % 3) != 0 {
            res |= (v % 3) << uint(k)
        }
    }
    fmt.Printf("res %+v\n", res)
    return res
}

Playground: https://play.golang.org/p/kaoSuesu2Oj

Output (Playground):

amd64p32
res -4
-4

Output (Local):

amd64
res -4
-4
🌐
Reddit
reddit.com › r/golang › behavior of converting uint32 --> int on 32-bit vs 64-bit systems
r/golang on Reddit: Behavior of converting uint32 --> int on 32-bit vs 64-bit systems
January 3, 2024 -

From what I understand, the size of the int type in Go is platform dependent.

From the docs (tour):

The int, uint, and uintptr types are usually 32 bits wide on 32-bit systems and 64 bits wide on 64-bit systems. When you need an integer value you should use int unless you have a specific reason to use a sized or unsigned integer type.

So, on a 32-bit system, if I did something like this:

var myUint32 uint32 = 4294967295 // max positive value for uint32

myInt := int(myUint32)

what would happen to myInt on a 32-bit system? I can't seem to find docs for this. Would the bitwise value remain the same in memory (and using a bit as a sign bit)? Or would there be truncation of some sort? I am unsure. I also don't have a quick way to test this out.

backstory, I have code in review that was suggested to be written like this:

func myFunc (a, b uint32) int {
    return int(a) - int(b)
}

I have a really bad feeling about this, especially since our code planned to be open source. There is no guarantee what architecture this will run on. But I need solid evidence argue we shouldn't do this.

🌐
Boyter
boyter.org › posts › cost-of-integer-cast-in-go
Cost of a integer cast in Go | Ben E. C. Boyter
August 22, 2022 - So about 0.5 ns for each operation. Which given the clock speed of the CPU means we are observing a single operation. With this as the baseline lets try the int to int32 cast.
🌐
Educative
educative.io › answers › what-is-type-int32-in-golang
What is type int32 in Golang?
int is one of the available numeric data types in Go used to store signed integers. int32 is a version of int that only stores signed numeric values composed of up to 32 bits.
🌐
Narkive
golang-nuts.narkive.com › BKuqQw0q › golang-type-casting-from-interface-int32-to-int
golang type casting from interface int32 to int
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/***@public.gmane.org For more options, visit https://groups.google.com/groups/opt_out. ... Post by Tong Sun Hi, I'm trying to assign a variable of type interface {} int32 to another variable - cannot use id (type interface {}) as type int in assignment: need type assertion - panic: interface conversion: interface is int32, not int - cannot use id.(int32) (type int32) as type int in assignment - invalid type assertion: id.(int32).(int) (non-interface type int32 on left)**** what's the proper way to do it?
🌐
GitHub
github.com › rung › go-safecast
GitHub - rung/go-safecast: Go Library for safe type conversion to prevent integer overflow · GitHub
You can use this library to prevent the vulnerability creation. (This library is inspired by Kubernetes's Security Audit Report by Trail of Bits) ... i := 2147483647 i32, err := safecast.Int32(i) // convert int to int32 in a safe way if err != nil { return err }
Starred by 18 users
Forked by 3 users
Languages   Go 90.2% | Makefile 9.8%
🌐
YourBasic
yourbasic.org › golang › convert-int-to-string
Convert between int, int64 and string · YourBasic Go
The fmt.Sprintf function is a useful general tool for converting data to string: s := fmt.Sprintf("%+8d", 97) // s == " +97" (width 8, right justify, always show sign) See this fmt cheat sheet for more about formatting integers and other types of data with the fmt package. Package strconv · golang.org · Pick the right one: int vs. int64 · An index, length or capacity should normally be an int. The types int8, int16, int32, and int64 are best suited for data.
Top answer
1 of 5
119

One line answer is fmt.Sprint(i).

Anyway there are many conversions, even inside standard library function like fmt.Sprint(i), so you have some options (try The Go Playground):


1- You may write your conversion function (Fastest):

func String(n int32) string {
    buf := [11]byte{}
    pos := len(buf)
    i := int64(n)
    signed := i < 0
    if signed {
        i = -i
    }
    for {
        pos--
        buf[pos], i = '0'+byte(i%10), i/10
        if i == 0 {
            if signed {
                pos--
                buf[pos] = '-'
            }
            return string(buf[pos:])
        }
    }
}

2- You may use fmt.Sprint(i) (Slow)
See inside:

// Sprint formats using the default formats for its operands and returns the resulting string.
// Spaces are added between operands when neither is a string.
func Sprint(a ...interface{}) string {
    p := newPrinter()
    p.doPrint(a)
    s := string(p.buf)
    p.free()
    return s
}

3- You may use strconv.Itoa(int(i)) (Fast)
See inside:

// Itoa is shorthand for FormatInt(int64(i), 10).
func Itoa(i int) string {
    return FormatInt(int64(i), 10)
}

4- You may use strconv.FormatInt(int64(i), 10) (Faster)
See inside:

// FormatInt returns the string representation of i in the given base,
// for 2 <= base <= 36. The result uses the lower-case letters 'a' to 'z'
// for digit values >= 10.
func FormatInt(i int64, base int) string {
    _, s := formatBits(nil, uint64(i), base, i < 0, false)
    return s
}

Comparison & Benchmark (with 50000000 iterations):

s = String(i)                       takes:  5.5923198s
s = String2(i)                      takes:  5.5923199s
s = strconv.FormatInt(int64(i), 10) takes:  5.9133382s
s = strconv.Itoa(int(i))            takes:  5.9763418s
s = fmt.Sprint(i)                   takes: 13.5697761s

Code:

package main

import (
    "fmt"
    //"strconv"
    "time"
)

func main() {
    var s string
    i := int32(-2147483648)
    t := time.Now()
    for j := 0; j < 50000000; j++ {
        s = String(i) //5.5923198s
        //s = String2(i) //5.5923199s
        //s = strconv.FormatInt(int64(i), 10) // 5.9133382s
        //s = strconv.Itoa(int(i)) //5.9763418s
        //s = fmt.Sprint(i) // 13.5697761s
    }
    fmt.Println(time.Since(t))
    fmt.Println(s)
}

func String(n int32) string {
    buf := [11]byte{}
    pos := len(buf)
    i := int64(n)
    signed := i < 0
    if signed {
        i = -i
    }
    for {
        pos--
        buf[pos], i = '0'+byte(i%10), i/10
        if i == 0 {
            if signed {
                pos--
                buf[pos] = '-'
            }
            return string(buf[pos:])
        }
    }
}

func String2(n int32) string {
    buf := [11]byte{}
    pos := len(buf)
    i, q := int64(n), int64(0)
    signed := i < 0
    if signed {
        i = -i
    }
    for {
        pos--
        q = i / 10
        buf[pos], i = '0'+byte(i-10*q), q
        if i == 0 {
            if signed {
                pos--
                buf[pos] = '-'
            }
            return string(buf[pos:])
        }
    }
}
2 of 5
14

The Sprint function converts a given value to string.

package main

import (
     "fmt"
)

func main() {

      var sampleInt int32 = 1

      sampleString := fmt.Sprint(sampleInt)
      fmt.Printf("%+V %+V\n", sampleInt, sampleString)
}

// %!V(int32=+1) %!V(string=1)

See this example.

🌐
Reddit
reddit.com › r/golang › converting int32 to uint64 and back to int32
r/golang on Reddit: Converting int32 to uint64 and back to int32
February 5, 2023 -

I am a bit concerned about a piece of code I wrote. It seems to work but I did not quite expect it to...

How does type conversion exactly work in Go when I convert a int32 to uint64 and then back to int32. I was somewhat scared that funny business might happen.

To give practical context of what I am doing. I have data like:

type data struct {
    a uint16
    b uint8
    c uint8
    d int32
}

Instead of using a data struct I want to package all the values in a single uint64 like:

data := uint64(a) | uint64(b)<<16 | uint64(c)<<24 | uint64(d)<<32

and then unpack it like (shifting back and applying a bit mask if necessary):

d := int32(data>>32)

my worries were around:

data = uint64(int32(d))

I was worried that it would try to do some conversion from int32 with negative values. But running some tests all it seems to be doing is padding or truncating bits and interpreting the two's compliment int values as uint.

Is this all safe and correct or am I about to run into nightmarish bugs?

Edit: In essence what I am asking with go type conversions does this hold for every value of d of type int32 :

d == int32(uint64(d))

🌐
Go language Tutorial
golangtutorial.dev › home › tips › how to convert an int32 & int64 to string in go
How to Convert an int32 & int64 to string in Go - Go language Tutorial
November 5, 2020 - strconv.Itoa accepts parameter of type int32 and converts it to string. package main import ( "strconv" "fmt" ) func main() { var intValue int = 100 var stringValue string stringValue = strconv.Itoa(intValue) fmt.Printf("%T, %v\n",intValue,intValue) fmt.Printf("%T, %v\n",stringValue,stringValue) }