Skip to content

Instantly share code, notes, and snippets.

@mdwhatcott
Created July 14, 2015 18:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mdwhatcott/fcd273934efe4c34167d to your computer and use it in GitHub Desktop.
Save mdwhatcott/fcd273934efe4c34167d to your computer and use it in GitHub Desktop.
package utils
// toInt is a port of the little endian path of the .Net BitConverter.ToInt32
// function. It does exactly what toIntReversed (below) does but it operates
// on a slice that is already in the expected order. If your slice is in
// reverse order, use toIntReversed (below) instead.
// For 4-byte integers the gist of this algorithm is:
// return int(b[0]) | int(b[1])<<8 | int(b[2])<<16 | int(b[3])<<24
// The for loop implementation allows byte slices of arbitrary length
// (up to 4 bytes because we return an int) to be converted to integer
// values appropriately.
func toInt(content []byte) int {
var value int32 = 0
for i, b := range content {
value |= int32(b) << uint(i*8)
}
return int(value)
}
// toInt64 operates exactly like toInt (above) but it converts to int64
// and thus receives byte slices up to 8 bytes (64 bits) in length.
func toInt64(content []byte) int64 {
var value int64 = 0
for i, b := range content {
value |= int64(b) << uint(i*8)
}
return value
}
// toIntReversed allows us to compute integer values from byte slices
// when the slice is received in reverse order. The old C# RDI code
// used to reverse the slice before calling BitConverter.ToInt32(...).
// This method allows us to skip the reversal of the slice when it would
// otherwise be needed.
// Credits: Rob Pike (http://commandcenter.blogspot.com/2012/04/byte-order-fallacy.html)
// For 4-byte integers the gist of this algorithm is:
// return int(b[0])<<24 | int(b[1])<<16 | int(b[2])<<8 | int(b[3])
// The for loop implementation allows byte slices of arbitrary length to be
// converted to integer values appropriately.
func toIntReversed(content []byte) (value int) {
shift := uint((len(content) - 1) * 8)
for _, b := range content {
value |= int(b) << shift
shift -= 8
}
return value
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment