Skip to content

Instantly share code, notes, and snippets.

@dermesser
Created January 31, 2015 16:17
Show Gist options
  • Save dermesser/163500e6fcaee7966490 to your computer and use it in GitHub Desktop.
Save dermesser/163500e6fcaee7966490 to your computer and use it in GitHub Desktop.
Encode and Decode uint64 values for sending them over the network or similar use cases. Fast (30 ns per number for both functions)
// Converts a number to a little-endian byte array
func lengthToBytes(l uint64) [8]byte {
var sizebuf [8]byte
var i int = 7
for ; i >= 0; i-- {
// The commented implementation is 5 times slower but equivalent
/*
var divisor uint64 = 1 << (uint(i) * 8)
sizebuf[i] = uint8(l / divisor)
l = l - ((l / divisor) * divisor)
*/
var shift uint = uint(i * 8)
sizebuf[i] = uint8((l & (255 << shift)) >> shift)
}
return sizebuf
}
// Gets the value from an encoded size number (lengthToBytes())
func sizebufToLength(b [8]byte) uint64 {
var size uint64 = 0
var i int = 7
for ; i >= 0; i-- {
var multiplier uint64 = 1 << (8 * uint(i))
size += multiplier * uint64(b[i])
// Bitshift is not faster
/*
var shift uint = 8 * uint(i)
size |= uint64(b[i]) << shift
*/
}
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment