I am very hard time to convert galois_mul2 function into javascript.
I am having following function in c
unsigned char galois_mul2(unsigned char value)
{
if (value >> 7)
{
return ((value << 1) ^ 0x1b);
}
else
return (value << 1);
}
Javascript Code
galois_mul2( value){
if (value >> 7)
{
return ((value << 1) ^ 0x1b);
}
else
return (value << 1);
}
If i give input 222 its return 167 in c code whereas in my code its return 423.
What's Problem?
As you probably know, numbers in JavaScript are 64-bit floats. But even if you have a UInt8Array
object, and index into it, JavaScript will convert the internal 8-bit number into a double before giving it to you, so value << 1
can become a 9-bit number: try var arr = new Uint8Array([222]); (arr[0] << 1).toString(2)
and notice the output is nine long.
To fix this, just mask with 0xFF
to keep the lowest eight bits:
function galois_mul2(value) {
if (value >> 7) {
return ((0xff & (value << 1)) ^ 0x1b);
}
return 0xff & (value << 1);
}
Then, galois_mul2(222)
returns 167.