Skip to content

Instantly share code, notes, and snippets.

@ecoshub
Last active December 9, 2023 18:27
Show Gist options
  • Star 17 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save ecoshub/5be18dc63ac64f3792693bb94f00662f to your computer and use it in GitHub Desktop.
Save ecoshub/5be18dc63ac64f3792693bb94f00662f to your computer and use it in GitHub Desktop.
golang integer to byte array and byte array to integer function
package main
import (
"fmt"
"unsafe"
)
func main(){
// integer for convert
num := int64(1354321354812)
fmt.Println("Original number:", num)
// integer to byte array
byteArr := IntToByteArray(num)
fmt.Println("Byte Array", byteArr)
// byte array to integer again
numAgain := ByteArrayToInt(byteArr)
fmt.Println("Converted number:", numAgain)
}
func IntToByteArray(num int64) []byte {
size := int(unsafe.Sizeof(num))
arr := make([]byte, size)
for i := 0 ; i < size ; i++ {
byt := *(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&num)) + uintptr(i)))
arr[i] = byt
}
return arr
}
func ByteArrayToInt(arr []byte) int64{
val := int64(0)
size := len(arr)
for i := 0 ; i < size ; i++ {
*(*uint8)(unsafe.Pointer(uintptr(unsafe.Pointer(&val)) + uintptr(i))) = arr[i]
}
return val
}
@The-Lumberjack
Copy link

gid:pGf2Haut6ocx4c3U6YFF6F

@ntsd
Copy link

ntsd commented Sep 13, 2022

Hi @ecoshub Can I use int instead of int64? and it will be fixed bytes size?

@ecoshub
Copy link
Author

ecoshub commented Sep 13, 2022

Ofcourse!. I cant see any problem with this. But remember its a 2.5 years old snippet :)) Even I dont like this code. You can use @stopcenz or @pyglue s snippets They are much more efficent. @stopcenz snippet is already int64

https://gist.github.com/ecoshub/5be18dc63ac64f3792693bb94f00662f?permalink_comment_id=4264235#gistcomment-4264235

@v0nc
Copy link

v0nc commented Sep 16, 2022

Hi @ecoshub Can I use int instead of int64? and it will be fixed bytes size?

Int isn't really a fixed size. On a 64bit system int is an int64 while on a 32bit system it will be an int32. So depending which system you compile your code for, you will end up with a different result.

@manosriram
Copy link

Do not use unsafe in production though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment