I have written the function FromBytes which converts bytes to integer format and passes it to IP4() based on endianness as follows:
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)
}
I need help writing a function which will convert from integer to bytes:
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
}
return ip[0], ip[1], ip[2], ip[3]assuming you want network order for the individual bytes. The endianness only matters for the native integer representation.FromBytesthe endianness check is appropriate, because you're taking a network order integer, stored in an array of bytes, and decoding it into a native integer type. However, doing it again for theOctetsmethod would potentially result in double reordering on a little endian arch.bufwithBigEndian, and use logical bitshifts like you do in your last comment, which operate on significant digits not on byte order.