jahly
jahly

Reputation: 3

Decoding integer value

I have this program that encodes integer values:

#include "stdafx.h"
#define _SECURE_SCL_DEPRECATE 0
#include <iostream>
#include <list>
#include <vector>
#include <algorithm>

using namespace std;

template<class T>
vector<unsigned char>  nToB(T );
unsigned long ByteToint(vector<unsigned char> v)
{
    unsigned long int a = 0;
    int s = v.size();
    for (int i = 0; i<s ; i++)
    {
        a |= (v[s - 1 - i] << (8 * (s - i - 1)));
    }
    return a;
}

static unsigned  long  int  Encode7Bits(unsigned long int);

int main()
{   
    cout << Encode7Bits(420);
    getchar();
    return 0;
}

static unsigned  long  int  Encode7Bits( unsigned long int x)
{
    vector<unsigned char> Result;

    do
    {
        unsigned long  int tmp = x & 0x7f;
        x = x >> 7;
        if (x > 0)
            tmp |= 0x80;        
        Result.push_back((unsigned char )tmp);
    } while (x > 0);

    return ByteToint(Result);
}

If the argument to this function is 420 it will return 932.

My question is whether it is possible to do the reverse operation, a decoding function that given 932, returns 420.

Upvotes: 0

Views: 185

Answers (1)

Bathsheba
Bathsheba

Reputation: 234635

No it isn't.

|= is non-invertible in the sense that if you write c = a | b, then given c, and either a or b, you can't recover the other variable.

The bitwise operators << and >> are obviously lossy since they introduce 0 bits.

You'll have better luck with XOR: if you write c = a ^ b, then c ^ b will be a.

Upvotes: 1

Related Questions