3

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
}
5
  • 1
    Endianness doesn't matter in this case, just 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. Commented Nov 10, 2016 at 4:47
  • what about FromBytes() does endiness check is needed. what is wrong with putting endianess check? Commented Nov 10, 2016 at 5:12
  • In FromBytes the 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 the Octets method would potentially result in double reordering on a little endian arch. Commented Nov 10, 2016 at 5:14
  • You mean: a, b, c, d = byte(ip>>24), byte(ip>>16), byte(ip>>8), byte(ip) with this solution I have tested. for bigendian, I am getting the octacts in reverse order. . Commented Nov 10, 2016 at 5:22
  • sorry, I was completely confused. Disregard everything. IP addresses are normally represented in network (big endian) order, so always read the buf with BigEndian, and use logical bitshifts like you do in your last comment, which operate on significant digits not on byte order. Commented Nov 10, 2016 at 5:39

1 Answer 1

5
b := make([]byte, 4) // 4 bytes for uint32.

binary.BigEndian.PutUint32(b, uint32(yourIP4))

// and

binary.LittleEndian.PutUint32(b, uint32(yourIP4))
Sign up to request clarification or add additional context in comments.

2 Comments

getting error cannot use ip (type IP4) as type uint32 in argument to binary.LittleEndian.PutUint32
@ravi_ss Edited the answer to add a uint32() cast around your IP4 values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.