Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert from integer to byte array using encoding/binary using Go based on endianness

Tags:

go

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
}
like image 739
ravi_ss Avatar asked Jul 24 '26 04:07

ravi_ss


1 Answers

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

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

// and

binary.LittleEndian.PutUint32(b, uint32(yourIP4))
like image 68
Nadh Avatar answered Jul 27 '26 07:07

Nadh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!