Created
January 31, 2015 16:17
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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