A simple integer array encoder with a very fast decoder

The post heading is enough for the explanation of the code I guess :) . This, surprisingly is a very nice technique given that you are constrained to use a c/c++ string for encoding an integer/floating point array. Comments are welcome as usual.

#include <cstdio>
#include <iostream>
#include <string>
#include <vector>

using namespace std;

void decoder(const char* ptr) {
  int *p = (int *)ptr;
  int size = *p;
  for (int i = 0; i < size; ++i) {
    ++p;
    printf("%d\n",*p);
  }
}

void encoder(const vector<int>& input, string *out) {
  int *arr = new int[input.size() + 1];
  arr[0] = input.size();
  for (int i = 0; i < input.size(); ++i) {
    arr[i + 1] = input[i];
  }
  const int size = arr[0] + 1;
  char encode[size * sizeof(int)];
  memcpy(encode, arr, size * sizeof(int));
  string encoder;
  for (int i = 0; i < size * sizeof(int); ++i) {
    encoder += encode[i];
  }
  out->assign(encoder);
  delete arr;
}

int main(int argc, char *argv[]) {
  vector<int> input;
  cout << "Enter the numbers. Enter -1 to stop.\n";
  int tmp = 0;
  while (1) {
    std::cin >> tmp;
    if (-1 == tmp) break;
    input.push_back(tmp);
  }
  string result;
  encoder(input, &result);
  std::cout << "Size of array now: " << result.size() << "\n";
  decoder(result.c_str());
  return 0;
}

Will try to add another code with a fast/size efficient encoder and possibly (intuitively) slower decoder.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 101 other followers