Are these two functions the same?
There is a function in the AES algorithm, to multiply a byte by 2 in Galois Field.
This is the function given in a website
private static byte gfmultby02(byte b)
{
if (b < 0x80)
return (byte)(int)(b <<1);
else
return (byte)( (int)(b << 1) ^ (int)(0x1b) );
}
This is the function i wrote.
private static byte MulGF2(byte x)
{
if (x < 0x80)
return (byte)(x << 1);
else
{
return (byte)((x &开发者_开发问答lt;< 1) ^ 0x1b);
}
}
What i need to know is, given any byte whether this will perform in the same manner. Actually I am worried about the extra cast to int and then again to byte. So far I have tested and it looks fine. Does the extra cast to int and then to byte make a difference in rare cases?
I think in this case the cast to int
does nothing, cause the cast is done after the left shift. So let's take a little example:
byte b = 0x1000;
//temp1 == 0x00000000;
int temp1 = (int)(b << 1);
//temp2 == 0x00010000;
int temp2 = ((int)b) << 1);
So as you can see the parentheses have a big impact on the result, but if took the formula from the website right, your code should behave the same.
I think it's correct, but:
The best way to make sure is to simply test it; there are only 256 cases and it shouldn't take many minutes to write the test case.
精彩评论