Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <cstdint>
- #include <cstdio>
- #include <cinttypes>
- namespace bitcompactor
- {
- template <typename T>
- T read_bits(const void *p, int first, int last)
- {
- int bits = last - first + 1;
- int offset = first;
- T dat = 0;
- const std::uint8_t *src = (std::uint8_t *)p;
- src += (offset/8);
- offset -= (offset/8) * 8;
- if (offset > 0) {
- dat |= *src >> offset;
- if (bits < 8) {
- dat &= ((1 << bits) - 1);
- }
- src++;
- offset = (8 - offset);
- bits -= offset;
- }
- while (bits >= 8) {
- dat |= *src << offset;
- src++;
- offset += 8;
- bits -= 8;
- }
- if (bits > 0) {
- dat |= (*src << offset) & (((1 << bits) - 1) << offset);
- }
- return dat;
- }
- // returns words written (characters)
- int translate(void *data_ptr, const int data_bits, char *output, const char *alphabet, const int word_bits)
- {
- typedef std::uint32_t T;
- int offset = 0;
- for (int i = 0; i < data_bits; i += word_bits) {
- T word = read_bits<T>(data_ptr, i, i + word_bits - 1);
- output[offset++] = alphabet[word];
- }
- // add null
- output[offset] = 0;
- return offset;
- }
- }
- int main(int argc, char **argv)
- {
- const char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345";
- // Oooh fabulous arms in the air, wiggle your hands and fingers
- std::uint64_t fabulous_data[2] =
- {
- 0xDEADBEEFFEEDF00D,
- // padding, translate() should/could if I wasn't lazy
- 0,
- };
- // DANGEROUS! ... my middle name is Danger ...
- // that's right, dr. Derek D. Danger Denkins ... -Smithe
- char output_string[128];
- int output_words = bitcompactor::translate(fabulous_data, 64, output_string, alphabet, 5);
- std::printf("FABULOUS!!! ... no wait ...\n");
- std::printf("fabulous_data = %" SCNxFAST64 "\n", fabulous_data[0]);
- std::printf("Fabulalphabet = %s\n", alphabet);
- std::printf("output_words = %i\n", output_words);
- std::printf("output_string = \"%s\"\n", output_string);
- // twas all for naught
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement