As a follow up to Store 2 4-bit numbers in 1 8 bit number, I am wondering if there is a generalization to it where you can store n x-bit numbers into m y-bit numbers. For example, maybe you can store 5 8-bit numbers into 3 15-bit numbers. Or maybe 2 8-bit numbers into 1 16-bit number, or 3 16-bit numbers into 2 32-bit numbers. Wondering what the implementation would be for encoding and decoding for a procedure that did this, or if it's not possible.
Something like:
function encode(i, s1, n, s2) {
// i = array of input bytes
// s1 = size of input bytes
// n = number of output bytes
// s2 = size of output bytes
}
function decode(i, s1, n, s2) {
}
Based on the answer below, I tried translating it to JavaScript but don't understand what anything really means and don't think it works.
function encode(input, inputSize, outputSize, callback) {
var buffer = 0
var bbits = 0
var mask = (1 << outputSize) - 1
while (bbits < outputSize) {
buffer |= (input << bbits)
bbits += inputSize
}
while (bbits >= outputSize) {
callback(buffer & mask)
buffer >>= outputSize
bbits -= outputSize
}
}