dsvbtgo639708 2016-12-28 15:51 采纳率: 0%
浏览 214

binary.Write()字节排序不适用于[] byte

package main

import (
    "encoding/binary"
    "fmt"
    "bytes"
)

func main(){
    b := new(bytes.Buffer)
    c := new(bytes.Buffer)
    binary.Write(b, binary.LittleEndian, []byte{0, 1})
    binary.Write(b, binary.BigEndian, []byte{0, 1})
    binary.Write(c, binary.LittleEndian, uint16(256))
    binary.Write(c, binary.BigEndian, uint16(256))
    fmt.Println(b.Bytes()) // [0 1 0 1]
    fmt.Println(c.Bytes()) // [0 1 1 0]
}

It is very interesting, why binary.Write() byte ordering is working for uint8, uint16, uint64..etc, but []byte?

If []byte need to be ordered by binary.LittleEndian and write to bytes.Buffer, it needs to be reversed first? Is there any effective ways to solve this problem?

Thanks.

  • 写回答

2条回答 默认 最新

  • dongpa5207 2016-12-28 16:08
    关注

    Only integer types get swapped by byte ordering.

    When it's a slice of bytes, the binary package wouldn't really know what to swap.

    For example, how would it know what to do if you passed 1k of data?

    Treat it as int16, int32 or int64?

    Or would you expect it to just reverse the whole slice?

    评论

报告相同问题?

悬赏问题

  • ¥15 基于单片机的靶位控制系统
  • ¥15 AT89C51控制8位八段数码管显示时钟。
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错