-
-
Save ecoshub/5be18dc63ac64f3792693bb94f00662f to your computer and use it in GitHub Desktop.
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 | |
} |
Hi @pyglue. I wrote for a custom network protocol. It use same encoder and decoder functions so endianness is not a problem. Also I love your method. I am gonna add your method to same benchmark below as "*_3" later.
Verify Github on Galxe. gid:pGf2Haut6ocx4c3U6YFF6F
gid:pGf2Haut6ocx4c3U6YFF6F
Hi @ecoshub Can I use int instead of int64? and it will be fixed bytes size?
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.
Do not use unsafe in production though.
@ecoshub : How long were the test-Strings in your BtoI tests? ππ»
not only in this part but also in production servers for 4 years π @mwat56
I wrote this not too long ago. Also as far as I know none of the examples above are specifically little- or big endian. This depends on your CPU and could (in theory) result in a big-endian byte array. Please correct me if I'm wrong tho ^^