binary.Write()函数对于[]byte类型的字节序写入不起作用。

huangapple go评论64阅读模式
英文:

binary.Write() byte ordering not working for []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]
}

很有趣,为什么 binary.Write() 对于 uint8, uint16, uint64 等类型的字节顺序起作用,但对于 []byte 类型却不起作用?

如果需要按照 binary.LittleEndian 的顺序对 []byte 进行排序并写入 bytes.Buffer,是否需要先进行反转?有没有有效的方法来解决这个问题?

谢谢。

英文:
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.

答案1

得分: 2

只有整数类型会受到字节顺序的影响。

当处理字节切片时,二进制包不会真正知道要进行什么样的交换。

例如,如果你传递了1k的数据,它会如何知道该怎么做呢?

将其视为int16、int32或int64吗?

还是你希望它只是将整个切片反转?

英文:

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?

答案2

得分: 2

因为没有需要排序的内容。一个字节是8位,所以你可以(无符号地)从0到255进行排序。例如,uint16有2个字节,所以你可以以不同的顺序对它们进行排序。

对于int8,甚至没有定义ByteOrder。你可以查看源代码,可以看到当类型为uint8int8时,binary.Write根本不使用传递的顺序。(byteuint8的别名)

英文:

Because there is nothing to order by. A byte is 8 bits, so you can go (unsigned) from 0 to 255. ie. uint16 you have 2 bytes, so you can order them differently.

ByteOrder is not even defined for int8. You can check the source code to see that binary.Write simply not uses the passed order when types are uint8 or int8. (A byte is an alias to uint8)

huangapple
  • 本文由 发表于 2016年12月28日 23:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41365443.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定