英文:
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]) << 8 |
uint64(b[2]) << 16 |
uint64(b[3]) << 24 |
uint64(b[4]) << 32 |
uint64(b[5]) << 40
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论