Created
December 29, 2018 22:17
-
-
Save vedhavyas/bdd57140594ea78fbc0bee6f9e98f211 to your computer and use it in GitHub Desktop.
Encode and Decode integers into []byte(inspired from a blog i couldn't find)
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
package main | |
import "fmt" | |
func main() { | |
nums := []int{256, 2, 100, 122234456, 10024} | |
fmt.Println(nums) | |
buf := encodeNumbers(nums...) | |
fmt.Println(buf) | |
fmt.Println(decodeNumbers(buf)) | |
} | |
// number - buf values... | |
// 1010101010101010 - none | |
// 101010101 - 10101010 | |
// 00000010 - 10101010, 11010101 | |
// 0 - 10101010, 11010101, 00000010 | |
func encodeNumbers(nums ...int) (buf []byte) { | |
for _, rem := range nums { | |
// start decomposing | |
for { | |
// get last 7 bits | |
v := rem & (0x7f) | |
// shift rem 7 to left | |
rem = rem >> 7 | |
// if rem == 0, append the bytes and return | |
if rem == 0 { | |
buf = append(buf, byte(v)) | |
break | |
} | |
// or the value with 8f so that we know we still have some bits to collect while decoding | |
v = v | 0x80 | |
buf = append(buf, byte(v)) | |
} | |
} | |
return buf | |
} | |
func decodeNumbers(buf []byte) (nums []int) { | |
var n, i int | |
for _, b := range buf { | |
// shift last 7 bits to number and then shift right and add to n. | |
n += int(b&0x7f) << (7 * uint(i)) | |
// check if 8th bit is set to 0, if so, that was the end of the number | |
if b&0x80 == 0 { | |
nums = append(nums, n) | |
n = 0 | |
i = 0 | |
continue | |
} | |
i++ | |
} | |
return nums | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment