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
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])<<8 | uint32(bs[0])<<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.