0

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.

1
  • 1
    This is a trapdoor function. Forget about inverting it. Commented Nov 24, 2017 at 8:49

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Same goes for x = x >> 7. Not invertable.
I feel like this misses the point though. The right shift and the OR are not what make this non-invertible, that part is just taking blocks of 7 bits and encoding them with a "continue"-bit, a pretty standard variable-length integer encoding. The problem is that this expands the output for high enough values, but the code forces the output back down to its original size.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.