Int64 to []byte and vice-versa

2,797 views
Skip to first unread message

Nikhilesh Susarla

unread,
Nov 21, 2022, 3:57:30 AM11/21/22
to golang-nuts
Hi, 

I have an int64 value say 12
I want to convert that to []byte array. 
How do we do that. There were lot of ways on the internet. Nothing which golang specifies or has a built-package for direct conversions. Lot of them dealt with Endiean's, but that might cause issues to I believe.

So, is there any one recommended and safe way? 
Thank you

Jan Mercl

unread,
Nov 21, 2022, 4:05:28 AM11/21/22
to Nikhilesh Susarla, golang-nuts
On Mon, Nov 21, 2022 at 9:57 AM Nikhilesh Susarla
<nikhil...@gmail.com> wrote:

> I have an int64 value say 12
> I want to convert that to []byte array.

Such conversion is not supported. Also, []byte is a slice.

However, the desired result can be computed in code. You can use the
encoding/binary package for that. Endianness matters, you cannot avoid
choosing one or another as that selects different results. In some
contexts the right endianness is platform independent, like in many
network/serialization protocols. In some other cases one has to follow
the platform endianness.

HTH.

Axel Wagner

unread,
Nov 21, 2022, 4:06:36 AM11/21/22
to Nikhilesh Susarla, golang-nuts
Use `encoding/binary`. Yes, you have to care about byte order. But that's inherent to the question. There is no canonical way in which an integer correspond to a slice of bytes, you actually have to say how to encode it. That also doesn't cause any problems - on the contrary, being explicit about that means you *don't* get into issues (for not knowing what byte order data is in). See also:

So, you probably want to do
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
and
v := int64(binary.BigEndian.Uint64(b))

On Mon, Nov 21, 2022 at 9:57 AM Nikhilesh Susarla <nikhil...@gmail.com> wrote:
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/dffa4b81-9c7b-48d8-8b8b-262804756606n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages