GoLang Int24转Int32

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

GoLang Int24 to Int32

问题

大家好,我用Go语言编写了这个函数,用于将24位整数(3个字节)转换为32位整数(4个字节)。

func int24ToInt32(bytes []byte) uint32 {
    return binary.BigEndian.Uint32(append([]byte{0x00}, bytes...))
}

我想知道这是否是解决问题的一个糟糕解决方案。也许有人可以指导我找到更好和更高效的解决方案。

英文:

Hi guys i wrote this function in GoLang to cast a 24 bit int (3 bytes) to a 32 bit int (4 bytes)

func int24ToInt32(bytes []byte) uint32 {
    return binary.BigEndian.Uint32(append([]byte{0x00}, bytes...))
}

I want to know if this is a bad solution to the problem. Maybe someone can guide me out to a better and efficient solution

答案1

得分: 6

你的解决方案非常易读,能够实现你的需求,并且速度足够快。

如果你想要进一步提高速度,你可以自己进行位移和或运算,代码如下:

func int24ToInt32(bs []byte) uint32 {
    return uint32(bs[2]) | uint32(bs[1])<<8 | uint32(bs[0])<<16
}

这段代码没有进行内存分配,并且不像标准库那样进行边界检查。它的速度也比使用binary包快几个数量级,但是我们谈论的是纳秒级别的差距,所以是否值得为了性能而牺牲可读性就是一个问题。

英文:

Your solution is very readable, does what you want, and is fast enough.

If you want to make it faster you can just do the bit shifting and or'ing yourself,

func int24ToInt32(bs []byte) uint32 {
	return uint32(bs[2]) | uint32(bs[1])&lt;&lt;8 | uint32(bs[0])&lt;&lt;16
}

This has no allocations, and doesn't do bounds checking like the standard library. It's also a couple orders of magnitude faster than using binary package, but we are talking nanoseconds so whether it is worth the hit to readability is really the question.

huangapple
  • 本文由 发表于 2017年8月29日 12:15:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/45930589.html
匿名

发表评论

匿名网友

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

确定