Is there a better or more idiomatic way in Go to encode a []byte slice into an int64?
package main
import "fmt"
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
var data int64
for i := 0; i < 8; i++ {
data |= int64(mySlice[i] & byte(255)) << uint((8*8)-((i+1)*8))
}
fmt.Println(data)
}
http://play.golang.org/p/VjaqeFkgBX
To convert a string to byte array or slice in Go language use the below one liner code. We can use byte array to store a collection of binary data, for example, the contents of a file. The above code to convert string to byte slice is very useful while using ioutil.WriteFile function, which accepts a bytes as its parameter:
If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv package Atoi method which convert string to int. package main import ( "fmt" "strconv" ) func main () { byteNumber := []byte ("14") byteToInt, _ := strconv.Atoi (string (byteNumber)) fmt.Println (byteToInt) }
The standard library of Go language provides the sort package which contains different types of sorting methods for sorting the slice of ints, float64s, and strings. These functions always sort the elements available is slice in ascending order.
I needed the Uint16 method. @TinkalGogoi use int64 (value) to convert a value to an int64. If []byte is ASCII byte numbers then first convert the []byte to string and use the strconv package Atoi method which convert string to int.
You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types
Play
package main
import "fmt"
import "encoding/binary"
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
data := binary.BigEndian.Uint64(mySlice)
fmt.Println(data)
}
It's almost overkill to use binary.BigEndian
, since it's such a tiny amount of code, and there's some clarity gained by being able to see exactly what's going on. But this is a highly contentious opinion, so your own taste and judgement may differ.
func main() {
var mySlice = []byte{123, 244, 244, 244, 244, 244, 244, 244}
data := uint64(0)
for _, b := range mySlice {
data = (data << 8) | uint64(b)
}
fmt.Printf("%x\n", data)
}
I'm not sure about idiomatic, but here's an alternative using the encoding/binary package:
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func main() {
var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
buf := bytes.NewReader(mySlice)
var data int64
err := binary.Read(buf, binary.LittleEndian, &data)
if err != nil {
fmt.Println("binary.Read failed:", err)
}
fmt.Println(data)
}
http://play.golang.org/p/MTyy5gIEp5
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