The Just Shall Live By Faith :D

I had posted something about fast encoding and decoding of integer array previously here. So here is something (maybe) more frequently used. A fast way to save space when you need to store large number of unsigned integers. I came up with two methods, one the evil but faster (exploiting the C features of C++) and the other which is more elegant, with similar performance in space but (might) slow down marginally. I’ll prefer the second, but C++ allows you to shoot yourself in the foot, so eager geeks go ahead :D

Using (non-recommended) C style type-casting:

#include <iostream>
#include <string>

using namespace std;

void EncodeNumber(unsigned int num, string* num_str) {
  unsigned char buf[4];
  unsigned char* ptr = (unsigned char*)&num;
  buf[0] = ptr[0];
  buf[1] = ptr[1];
  buf[2] = ptr[2];
  buf[3] = ptr[3];
  num_str->assign((const char*)buf, 4);
}

void DecodeNumber(const string& num_str, unsigned int* num) {
  const unsigned int* a = (const unsigned int*)num_str.c_str();
  *num = *a;
}

int main() {
  unsigned int num;
  cin >> num;
  string num_str;
  EncodeNumber(num, &num_str);
  cout << "String format of number: " << num_str << endl;
  DecodeNumber(num_str, &num);
  cout << "Decoded number: " << num << endl;
  return 0;
}

The one using (recommended) C++ style type-casting:

#include <iostream>
#include <string>

using namespace std;

void EncodeNumber(unsigned int num, string* num_str) {
  unsigned char buf[4];
  buf[3] = num >> 24; num <<= 8; num >>= 8;
  buf[2] = num >> 16; num <<= 16; num >>= 16;
  buf[1] = num >> 8; num <<= 24; num >>= 24;
  buf[0] = num;
  num_str->assign(reinterpret_cast<const char*>(buf), 4);
}

void DecodeNumber(const string& num_str, unsigned int* num) {
  const unsigned int* a
      = reinterpret_cast<const unsigned int*>(num_str.c_str());
  *num = *a;
}

int main() {
  unsigned int num;
  cin >> num;
  string num_str;
  EncodeNumber(num, &num_str);
  cout << "String format of number: " << num_str << endl;
  DecodeNumber(num_str, &num);
  cout << "Decoded number: " << num << endl;
  return 0;
}

PS1: The encoding and decoding is assured to work if both are done on machines with same endianness and will break if different for encoding and decoding.
PS2: All this was done while waiting for a computationally intensive task to complete. Unfortunately this can’t speed it up :( . Hope (at least) someone finds some use of this :)

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 102 other followers