Reputation: 69
sI've been having some trouble with this function for a bit now. I managed to reverse it out of some assembly code, and have gotten it to work perfectly. But I can't do the opposite of what it does. Here is what I mean:
Here is my code
ushort storedVal = 12525; //Value to extract actual index out of
byte[] block = BitConverter.GetBytes(storedVal);
uint aVal = block[0];
uint bVal = block[1];
uint index = Convert.ToUInt32((aVal >> 2) & 0x300) | bVal; //Extracting actual index
As you can see, it performs a Bitshift (to the right by 2), an AND on the result on the bitshift, and then ORs the result of that by bVal (or the second byte in the byte array of 12525).
The result that is stored in index is an index into a table/list. In this case it is 48/
I'm having trouble getting that index back into a number like that. Basically undoing what that code does.
Upvotes: 3
Views: 172
Reputation: 6515
There's either a bug in your code or you've transcribed it incorrectly. aVal
is a byte, so (aVal >> 2) & 0x300
is always going to be zero. This means that index
has the same value as bVal
, which is the first byte of storedVal
. This means that you can rewrite the whole function as (storedVal >> 8)
. Therefore, given the return value of this function you can easily determine one byte of the input, but the other byte could have been anything (since it doesn't affect the output).
Upvotes: 0
Reputation: 35901
If the input value is ushort
then you can easily find the preimage of the argument with brute-force approach. However, because the function is not reversible you're likely to get more than one result:
public static uint getIndex(ushort value)
{
byte[] block = BitConverter.GetBytes(value);
uint aVal = block[0];
uint bVal = block[1];
return Convert.ToUInt32((aVal >> 2) & 0x300) | bVal;
}
public static void Main()
{
uint givenIndex = 192;
for (ushort i = ushort.MinValue;;++i)
{
if (givenIndex == getIndex(i))
{
Console.WriteLine("Possible input: " + i);
}
if (i == ushort.MaxValue)
{
break;
}
}
}
Note also that for some arguments you won't get any results, as the function is also not a surjection.
Upvotes: 1
Reputation: 22323
There isn't enough information in the index to get back to the original value. to perform a reverse of the operation here, you would need to know the aVal
and the bVal
used to reach the index, which aren't being stored. without knowing these, the reverse function has infinite answers.
Upvotes: 1