我编写了函数FromBytes
,它将字节转换为整数格式,并根据字节顺序将其传递给IP4()
,如下所示:
type IP4 uint32
func FromBytes(ip []byte) IP4 {
var pi IP4
buf := bytes.NewReader(ip)
if <little endian>
err := binary.Read(buf, binary.LittleEndian, &pi)
else
err := binary.Read(buf, binary.BigEndian, &pi)
if err != nil {
fmt.Println("binary.Read failed:", err)
}
return IP4(pi)
}
我需要帮助编写一个将从整数转换为字节的函数:
func (ip IP4) Octets() (a, b, c, d byte) {
if <little endian>
// code to convert from integer to bytes for little endian
} else {
// code to convert from integer to bytes for big endian
}
return
}
答案 0 :(得分:2)
b := make([]byte, 4) // 4 bytes for uint32.
binary.BigEndian.PutUint32(b, uint32(yourIP4))
// and
binary.LittleEndian.PutUint32(b, uint32(yourIP4))