snippetgoModerate
Effectively convert little endian byte slice to int32
Viewed 0 times
convertbyteendianeffectivelyint32littleslice
Problem
I have a data stream of bytes and I'd like to get a little endian encoded int32 from four bytes. Is there a better way than to do this like the following code?
The code above seems to work fine, but perhaps there is a built-in function in Go that I've missed or there is a super cool hack that does that in one instruction?
package main
func read_int32(data []byte) int32 {
return int32(uint32(data[0]) + uint32(data[1])<<8 + uint32(data[2])<<16 + uint32(data[3])<<24)
}
func main() {
println(read_int32([]byte{0xFE,0xFF,0xFF,0xFF})) // -2
println(read_int32([]byte{0xFF,0x00,0x00,0x00})) // 255
}The code above seems to work fine, but perhaps there is a built-in function in Go that I've missed or there is a super cool hack that does that in one instruction?
Solution
encoding/binary package may have what you need. Check this: http://golang.org/pkg/encoding/binary/#example_ReadYour code with modified
read_int32 function could be:package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func read_int32(data []byte) (ret int32) {
buf := bytes.NewBuffer(data)
binary.Read(buf, binary.LittleEndian, &ret)
return
}
func main() {
fmt.Println(read_int32([]byte{0xFE, 0xFF, 0xFF, 0xFF})) // -2
fmt.Println(read_int32([]byte{0xFF, 0x00, 0x00, 0x00})) // 255
}Also you can interpret big endian by replacing
binary.LittleEndian with binary.BigEndianCode Snippets
package main
import (
"bytes"
"encoding/binary"
"fmt"
)
func read_int32(data []byte) (ret int32) {
buf := bytes.NewBuffer(data)
binary.Read(buf, binary.LittleEndian, &ret)
return
}
func main() {
fmt.Println(read_int32([]byte{0xFE, 0xFF, 0xFF, 0xFF})) // -2
fmt.Println(read_int32([]byte{0xFF, 0x00, 0x00, 0x00})) // 255
}Context
StackExchange Code Review Q#15945, answer score: 16
Revisions (0)
No revisions yet.