I'm doing some work with integer compression.
I've implemented variable-byte encoding algorithm in c++ (see the snippet below).
I wonder how to implement it in golang since I cannot convert string
or tune
type between int
type in memory as memcpy()
does.
Then, I've figured out binary.Write()
in package encoding/binary
can do the serializing work, which can encode uint8 into one byte, unint16 into 2 bytes, uint32 in 4 types and so on.
But how to encode a integer, which is between 2097152 and 268435456, using only 3 bytes ?
Is there any similar converting method like the snippet ?
void encode(int value, char* code_list, int& len) {
int bit_value = 0;
int bit_num = 0;
if (value < 128) {
bit_num = 1;
} else if (value < 16384) {
bit_num = 2;
bit_value = 1;
} else if (value < 2097152) {
bit_num = 3;
bit_value = 3;
} else {
bit_num = 4;
bit_value = 7;
}
value <<= bit_num;
value += bit_value;
memcpy(code_list + len, (char*) &value, bit_num);
len += bit_num;
}