[H]ow to convert *int64 to *int32?

You cannot.

Use var i32 int32 = int32(*x); t2(&i32); *x=int64(i32).

Answer from Volker on Stack Overflow
🌐
GitHub
github.com › JohnCGriffin › overflow
GitHub - JohnCGriffin/overflow: Check for int/int64/int32 arithmetic overflow in Golang
Check for int/int8/int16/int64/int32 integer overflow in Golang arithmetic. ... Note that because Go has no template types, the majority of repetitive code is generated by overflow_template.sh. If you have to change an algorithm, change it there and regenerate the Go code via:
Starred by 46 users
Forked by 14 users
Languages   Go 84.5% | Shell 15.5% | Go 84.5% | Shell 15.5%
🌐
GitHub
github.com › rung › go-safecast
GitHub - rung/go-safecast: Go Library for safe type conversion to prevent integer overflow · GitHub
The type of int equals int64 on 64-bit machine in Go. When you convert int(int64) to int32, int8 or int6, Your code could have Integer Overflow vulnerability.
Starred by 18 users
Forked by 3 users
Languages   Go 90.2% | Makefile 9.8%
Discussions

go - how to convert *int64 to *int32? - Stack Overflow
I have a *int64 as one of the parameters in my function, and I need to convert it to *int32 to meet the definition of the function I want to call. func t1(x *int64) error { var y *int32 ... More on stackoverflow.com
🌐 stackoverflow.com
Int overflow in tokenJSON.ExpirationTime (casting int64 to int32)
TokenJSON expirationTime is typed to int32. The unmarshal code further cast int64 to int32 expirationTime should just be int64. This is an issue when some apps return really long expiration time to indicate permanent tokens, causing int ... More on github.com
🌐 github.com
3
May 4, 2018
Converting int32 to uint64 and back to int32
If your input is always int32, then you won't run into issues with converting between the 2. If your input is int64 you will definitely run into issues at some point. So, ensure your codepaths don't allow for user input of the wrong precision. More on reddit.com
🌐 r/golang
16
4
February 5, 2023
Behavior of converting uint32 --> int on 32-bit vs 64-bit systems
https://go.dev/play/p/lSJ2sDH2s_O would be equivalent to what you're asking about, int isn't any different than the more explicit int32 or int64 types. Any conversion from a max uint value to the equivalent int type will yield the same result, -1. I read the spec and the conversion section doesn't mention anything specific about converting from unsigned to signed integers in an overflow situation unfortunately, but I think evaluating to -1 is pretty typical. https://go.dev/ref/spec#Conversions More on reddit.com
🌐 r/golang
11
4
January 3, 2024
🌐
rene's blog
blog.rene.sh › blog › 2020 › 06 › 22 › int-overflow
Integer Overflows in Golang – rene's blog
June 22, 2020 - package main import ( "errors" "fmt" "math" ) var ErrOverflow = errors.New("integer overflow") func Add32(left, right int32) (int32, error) { if right > 0 { if left > math.MaxInt32-right { return 0, ErrOverflow } } else { if left < math.MinInt32-right { return 0, ErrOverflow } } return left + right, nil } func main() { var a, b int32 = 2147483327, 2147483327 c, err := Add32(a, b) if err != nil { // handle overflow fmt.Println(err, a, b, c) } }
🌐
Hyperskill
hyperskill.org › learn › step › 18710
Type conversion and overflow
Hyperskill is an educational platform for learning programming and software development through project-based courses, that helps you secure a job in tech. Master Python, Java, Kotlin, and more with real-world coding challenges.
🌐
Educative
educative.io › answers › what-is-type-int64-in-golang
What is type int64 in Golang?
So, for example, if you try to store a string value in it, or an integer beyond what can be made using 64 bits, the program would return an error or result in an integer overflow.
🌐
Go Packages
pkg.go.dev › github.com › rwxe › overflow
overflow package - github.com/rwxe/overflow - Go Packages
November 19, 2023 - Package overflow offers overflow-checked integer arithmetic operations for int, int32, and int64.
Find elsewhere
🌐
GitHub
github.com › golang › oauth2 › issues › 279
Int overflow in tokenJSON.ExpirationTime (casting int64 to int32) · Issue #279 · golang/oauth2
May 4, 2018 - TokenJSON expirationTime is typed to int32. The unmarshal code further cast int64 to int32 expirationTime should just be int64. This is an issue when some apps return really long expiration time to indicate permanent tokens, causing int ...
Author   j3ch
🌐
LabEx
labex.io › tutorials › go-how-to-avoid-integer-casting-mistakes-446329
How to avoid integer casting mistakes | LabEx
Be aware of potential overflow when converting between types ... By understanding these integer type basics, developers using LabEx can write more efficient and error-resistant Go code. Go requires explicit type conversion for different integer types, unlike some other languages that perform implicit conversions. package main import "fmt" func main() { var a int32 = 42 var b int64 = int64(a) // Explicit conversion fmt.Printf("Converted value: %d\n", b) }
🌐
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))

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

🌐
Stack Overflow
stackoverflow.com › questions › 73503428 › golang-untyped-int-overflow-on-32-bit-arm
linux - Golang untyped int overflow on 32-bit arm - Stack Overflow
This might be explained with a particular interpretation of the language spec about untyped constants. It looks like 0xF3210123 is interpreted as an uint32 value, which then causes overflow when converted to a int32 value at compile time.
🌐
Reddit
reddit.com › r/golang › using int32 for efficiency or simply stick to int64?
r/golang on Reddit: Using int32 for efficiency or simply stick to int64?
January 30, 2022 -

I have a field in my data which is small enough to simply use an int32. However, from what I can tell, int32 is generally used when representing a code point or something quite specific, rather than using it simply to save 32 bits of storage. Also, some of the stdlib packages (like strconv) deal exclusively with int64 rather than int32. This has meant changes to my code I didn't expect purely to handle int32 things.

What is your opinion (and perhaps the general consensus) on using int32 purely for efficiency purposes? Is it just worth using an int64 for simplicity?

🌐
GitHub
github.com › influxdata › telegraf › issues › 15798
Linter: gosec, Rule: G115 - Potential integer overflow when converting between integer types. Should we enable it? · Issue #15798 · influxdata/telegraf
September 1, 2024 - For this rule following findings were found in current code: cmd/telegraf/cmd_secretstore.go:239:39 gosec G115: integer overflow conversion uintptr -> int internal/process/process.go:133:33 gosec G115: integer overflow conversion int -> int32 internal/snmp/field.go:184:13 gosec G115: integer overflow conversion uint -> int64 internal/snmp/field.go:192:13 gosec G115: integer overflow conversion uint64 -> int64 internal/snmp/wrapper.go:191:18 gosec G115: integer overflow conversion uint64 -> uint16 internal/type_conversions.go:176:17 gosec G115: integer overflow conversion uint64 -> uint32 inter
Author   zak-pawel
🌐
Medium
medium.com › @griffinish › integer-overflow-in-golang-9e13e274c8a5
Integer Overflow in Golang. For efficiency, Golang does not check… | by John Griffin | Medium
July 18, 2017 - Integer Overflow in Golang For efficiency, Golang does not check for overflow. In that legitimate design decision, Golang keeps the company of C, C++, and Java. While ignoring overflow is efficient …
Top answer
1 of 2
3

You can use the generics approach to have compile-time guarantees about what types are accepted — with a small modification to make it more broadly useful — but that won't help when targeting different architectures. For that, you can use build constraints so that the appropriate version of your function is compiled into the executable.

As an example, build for 32-bit linux:

//go:build linux && 386

func ConvertUintT ~uint | ~uint32 uint {
    return uint(x)
}

or build for 64-bit MacOS with Apple chip:

//go:build darwin && arm64

func ConvertUintT ~uint | ~uint32 | ~uint64 uint {
    return uint(x)
}

I used random build tags as an example. Your actual build conditions could be more complex than that. You can see which are Go's supported distributions, and have an idea of what build tags you might use with:

go tool dist list

When building with go build, the toolchain will pick up the GOOS and GOARCH environment variables and build the appropriate file. Otherwise you can pass the tags explicitly to the build command as shown in this question.

2 of 2
0

I don't know of a very clean approach, but if there potentially a bunch of different types that you want to allow to be cast to uint, then instead of defining a separate function for each such cast, another option is to define an interface with the appropriate set of types, and then define a generic function that's defined only for types in that set:

type SafeToConvertToUInt interface {
    uint | uint32 | uint64
}

func ToUIntT SafeToConvertToUInt uint {
    return uint(x)
}

[playground link]

🌐
GitHub
github.com › securego › gosec › issues › 1130
Add detection of overflow during integer conversion · Issue #1130 · securego/gosec
April 25, 2024 - Summary G109 provides detection of overflow during strconv.Atoi, but there seems to be no good way to detect the more common conversions between integers, such as uint32 to int32. Steps to reproduce the behavior gosec version Go version ...
Author   findmyhappy
🌐
GitHub
github.com › securego › gosec › issues › 1185
G115: integer overflow conversion uint8 -> int64 · Issue #1185 · securego/gosec
August 20, 2024 - Summary uint8 -> int64 has no overflow Steps to reproduce the behavior package main import ( "fmt" ) func main() { str := "A\xFF" i := int64(str[0]) fmt.Printf("%d\n", i) } gosec version 81cda2f Go version (output of 'go version') go ver...
Author   ldemailly