Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert an int64 into a byte array in go?

Tags:

casting

go

I have an id that is represented at an int64. How can I convert this to a []byte? I see that the binary package does this for uints, but I want to make sure I don't break negative numbers.

like image 543
Charles L. Avatar asked Feb 12 '16 20:02

Charles L.


People also ask

What is byte array in Golang?

A byte in Go is an unsigned 8-bit integer. It has type uint8 . A byte has a limit of 0 – 255 in numerical range. It can represent an ASCII character. Go uses rune , which has type int32 , to deal with multibyte characters.

How many bytes is a Go?

Rune. Like byte type, Go has another integer type rune . It is aliases for int32 (4 bytes) data types and is equal to int32 in all ways.

What is byte value in Golang?

The byte type in Golang is an alias for the unsigned integer 8 type ( uint8 ). The byte type is only used to semantically distinguish between an unsigned integer 8 and a byte. The range of a byte is 0 to 255 (same as uint8 ).


2 Answers

Converting between int64 and uint64 doesn't change the sign bit, only the way it's interpreted.

You can use Uint64 and PutUint64 with the correct ByteOrder

http://play.golang.org/p/wN3ZlB40wH

i := int64(-123456789)  fmt.Println(i)  b := make([]byte, 8) binary.LittleEndian.PutUint64(b, uint64(i))  fmt.Println(b)  i = int64(binary.LittleEndian.Uint64(b)) fmt.Println(i) 

output:

-123456789 [235 50 164 248 255 255 255 255] -123456789 
like image 178
JimB Avatar answered Sep 17 '22 11:09

JimB


You can use this too:

var num int64 = -123456789  b := []byte(strconv.FormatInt(num, 10))  fmt.Printf("num is: %v, in string is: %s", b, string(b)) 

Output:

num is: [45 49 50 51 52 53 54 55 56 57], in string is: -123456789 
like image 30
Jonathan Hecl Avatar answered Sep 17 '22 11:09

Jonathan Hecl