简体   繁体   中英

How do I reverse the following algorithm in C

I have the following algorithm:

    unsigned long specialNum=0x4E67C6A7;
    unsigned int ch;
    char inputVal[]="                        AAPB2GXG";


    for(int i=0;i<strlen(inputVal);i++)
    {
        ch=inputVal[i];

        ch=ch+(specialNum*32);
        ch=ch+(specialNum/4);

        specialNum=bitXor(specialNum,ch);
    }

    int outputVal=specialNum;

The bitXor simply does the Xor operation:

int bitXor(int a,int b)
{
    return (a & ~b) | (~a & b);
}

Now I want to reverse The Algorithm . Given the outputVal, I want to get the inputVal. This is what I have done till now. But it is not working :(

    while(outputVal!=0x4E67C6A7)
    {
        ch=bitXor(outputVal,0x4E67C6A7);

        outputVal=outputVal-(ch*4);
        outputVal=outputVal-(ch/32);
        inputVal[i++]=(char)ch;
        if(i>32)
            break;
    }

EDIT: Ok, agreed its not possible. But I wonder why is my question downvoted. I have followed the guidelines before posting and I dont think the question is too bad for downvoting it.

In the requested "reversed" algorithm you are asking for converting 4-byte number into an arbitrary-length string. It is obviously not possible, since assuming you are doing this, you have invented an ultimate compression algorithm.

The "reverse algorithm" you are asking for is impossible. Your example inputVal is a character string over 30 letters long. Your outputVal is 4 or 8 bytes at best. Information theory dictates that it's impossible to store any arbitrary n-byte string into a k-byte string if n > k.

Your forward algorithm is basically bit-packing values from the array inputVal into the scalar variable specialNum in an awkward way.

Also, at the end there is an unsafe conversion from unsigned long specialNum to int outputVal .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM