bytes与32位int互转
package main
import (
"fmt"
"reflect"
)
func intToBytes(num int) []byte {
bytes := []byte{0, 0, 0, 0}
bytes[3] = (byte)((num >> 24) & 0xFF)
bytes[2] = (byte)((num >> 16) & 0xFF)
bytes[1] = (byte)((num >> 8) & 0xFF)
bytes[0] = (byte)(num & 0xFF)
return bytes
}
func bytesToInt(bytes []byte) (num int) {
num = (num | int(bytes[0])) + (num | int(bytes[1])<<8) + (num | int(bytes[2])<<16) + (num | int(bytes[3])<<24)
return
}
func main() {
a := intToBytes(123123)
fmt.Println(a)
fmt.Println(int(bytesToInt(a)))
}
网友评论