dq62957 2016-11-10 04:29
浏览 90

使用基于字节序的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
}
  • 写回答

1条回答 默认 最新

  • dongyou6768 2016-11-10 05:48
    关注
    b := make([]byte, 4) // 4 bytes for uint32.
    
    binary.BigEndian.PutUint32(b, uint32(yourIP4))
    
    // and
    
    binary.LittleEndian.PutUint32(b, uint32(yourIP4))
    
    评论

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码