Skip to content

Instantly share code, notes, and snippets.

@hugows
Last active September 12, 2016 13:21
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 hugows/7b7358468119e046387ab4f782c8fc20 to your computer and use it in GitHub Desktop.
Save hugows/7b7358468119e046387ab4f782c8fc20 to your computer and use it in GitHub Desktop.
/* from http://number-none.com/product/Packing%20Integers/index.html */
#include <stdio.h>
#include <stddef.h>
#include <stdint.h>
static uint32_t m_accumulator = 0;
static char m_buffer[17];
char* to_bitstring(uint32_t val, char buffer[], int size) {
buffer[--size] = 0;
while (size > 0) {
buffer[--size] = (val % 2 ? '1' : '0');
val = val >> 1;
}
return buffer; /* convenience */
}
void pack(uint32_t limit, uint32_t value) {
m_accumulator = (limit * m_accumulator) + value;
to_bitstring(m_accumulator, m_buffer, sizeof(m_buffer));
printf("packing %d - 0x%08x [%s]\n", value, m_accumulator, m_buffer);
}
uint32_t unpack(uint32_t limit) {
uint32_t quotient = m_accumulator / limit;
uint32_t remainder = m_accumulator % limit;
m_accumulator = quotient;
return remainder;
}
int main(int argc, char const *argv[])
{
int val;
pack(10, 2);
pack(10, 3);
pack(10, 9);
pack(10, 5);
pack(10, 4);
do {
val = unpack(10);
printf("%d\n", val);
} while (val != 0);
/* awesome trick from Jon Blow... */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment