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.
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.
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.
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 ).
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With