Convert 3 bytes to int in go?

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

Convert 3 bytes to int in go?

问题

我知道如何使用"encoding/binary"将4个字节转换为整数等。

将只有3个字节转换为整数的最有效方法是什么?

英文:

I know how to use "encoding/binary" to convert 4 bytes to an int, etc.

What is the most efficient way to convert just 3 bytes to an int?

答案1

得分: 9

小端序:

n := int(uint(b[0]) | uint(b[1])<<8 | uint(b[2])<<16))

大端序:

n := int(uint(b[2]) | uint(b[1])<<8 | uint(b[0])<<16))
英文:

Little endian:

n := int(uint(b[0]) | uint(b[1])&lt;&lt;8 | uint(b[2])&lt;&lt;16))

Big endian:

n := int(uint(b[2]) | uint(b[1])&lt;&lt;8 | uint(b[0])&lt;&lt;16))

huangapple
  • 本文由 发表于 2017年7月10日 05:01:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/45000982.html
匿名

发表评论

匿名网友

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

确定