Created
March 25, 2019 12:53
-
-
Save Elfsong/a1b44bbb48780bc27cff427b1a3e070e to your computer and use it in GitHub Desktop.
V_Byte#python
This file contains hidden or 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
def vbyte_encode(num): | |
# out_bytes stores a list of output bytes encoding the number | |
out_bytes = [] | |
### | |
# Your answer BEGINS HERE | |
### | |
while num >= 128: | |
out_bytes = [num % 128] + out_bytes | |
num = num >> 7 | |
out_bytes = [num + 128] + out_bytes | |
### | |
# Your answer ENDS HERE | |
### | |
return out_bytes | |
def vbyte_decode(input_bytes, idx): | |
# x stores the decoded number | |
x = 0 | |
# consumed stores the number of bytes consumed to decode the number | |
consumed = 0 | |
### | |
# Your answer BEGINS HERE | |
### | |
x = int("".join(input_bytes[0]),2) - 128 | |
for item in input_bytes[1:]: | |
x = x * 128 + int("".join(item),2) | |
consumed = len(input_bytes) | |
### | |
# Your answer ENDS HERE | |
### | |
return x, consumed |
This file contains hidden or 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
def vbyte_encode(num): | |
# out_bytes stores a list of output bytes encoding the number | |
out_bytes = [] | |
### | |
# Your answer BEGINS HERE | |
### | |
while num >= 128: | |
out_bytes = [num % 128] + out_bytes | |
num = num >> 7 | |
out_bytes = [num + 128] + out_bytes | |
### | |
# Your answer ENDS HERE | |
### | |
return out_bytes | |
def vbyte_decode(input_bytes, idx): | |
# x stores the decoded number | |
x = 0 | |
# consumed stores the number of bytes consumed to decode the number | |
consumed = 0 | |
### | |
# Your answer BEGINS HERE | |
### | |
x = input_bytes[0] - 128 | |
for item in input_bytes[1:]: | |
x = x * 128 + item | |
consumed = len(input_bytes) | |
### | |
# Your answer ENDS HERE | |
### | |
return x, consumed |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment