将一个6字节的切片转换为小端序。

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

converting a 6 byte slice to to little endian

问题

我想将一个6字节的切片转换为小端编码。

我正在使用字节切片解析一个数组,并使用binary包的Read函数将它们转换为小端编码。但是当我解析一个6字节的切片,例如{05,00,00,00,00,00},它返回零(十六进制表示),数据接口为uint64。有没有办法使用上述函数而不是硬编码来实现这一点。请注意,如果我用零填充剩余的两个字节,我可以得到结果,但是我的解析器似乎漏掉了数组的后两个字节。

谢谢你的帮助和建议。

英文:

I want to convert a 6 byte slice to little Endian encoding.

I am parsing an array using byte slices and converting them to little Endian using The Read function of binary package. But When I parse a 6 byte slice e.g. {05,00,00,00,00,00} it returns zero (hex notation) with data interface being uint64. Is there any way to do this using the above function and not hardcoding it. Note that if I pad the residual two bytes zeros I get the result but somehow the my parser misses the following two bytes of the array.

Thanks for your help/suggestions.

答案1

得分: 1

手动解码它很简单:

b := []byte{5,0,0,0,0,0,0}
i := uint64(b[0]) |
     uint64(b[1]) << 8 |
     uint64(b[2]) << 16 |
     uint64(b[3]) << 24 |
     uint64(b[4]) << 32 |
     uint64(b[5]) << 40

将其手动解码即可。

英文:

Decode it by hand. It's trivial:

b := []byte{5,0,0,0,0,0,0}
i := uint64(b[0]) |
     uint64(b[1]) &lt;&lt; 8 |
     uint64(b[2]) &lt;&lt; 16 |
     uint64(b[3]) &lt;&lt; 24 |
     uint64(b[4]) &lt;&lt; 32 |
     uint64(b[5]) &lt;&lt; 40

huangapple
  • 本文由 发表于 2013年9月27日 02:49:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/19036292.html
匿名

发表评论

匿名网友

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

确定