java - What is wrong with this implementation of bitwise multiplication? -
i attempting implement method bitwise multiplication in galois field 256 sake of building implementation of aes. current multiplication method follows:
public static int multiplypolynomials(int n, int m) { int result = 0x00000000; string ns = tobitstring(n); string ms = tobitstring(m); (int = 0; < ns.length(); i++) { if (ns.charat(i) == '1') { /* * if there's 1 @ place i, add value of m left-shifted places result. */ int temp = m; (int j = 0; j < i; j++) { temp = temp << 1; } result += temp; } } return result; }
the tobitstring(int n)
method purely shortcut integer.tobinarystring(int n)
.
given input of (0x0000ef00, 2)
, output of function 494 (should 478). printing direct call tobitstring(0x0000ef00)
confirms output of function expected (in case, 1110111100000000). if first input shifted 1 byte right (0x000000ef) output still 494.
with above inputs, value of ns 1110111100000000
, bit-string equivalent of result
111101110
. ns
correct.
what error in method above?
you reading binary string wrong way round.
try this...
public static int multiplypolynomials(int n, int m) { int result = 0x00000000; string ns = integer.tobinarystring(n); (int = 0; < ns.length(); i++) { // read string other way round... int bitindex = (ns.length() - i) - 1; if (ns.charat(bitindex) == '1') { /* * if there's 1 @ place i, add value of m left-shifted * places result. */ int temp = m; // don't need loop here, shift "i" places temp = temp << i; result += temp; } } return result; }
instead of turning number binary string, use instead...
public static int multiplypolynomials(int n, int m) { int result = 0x00000000; (int = 0; < 32; i++) { int mask = 1 << i; if ((n & mask) == mask) { result += m << i; } } return result; }
you might need store answer long prevent overflows , won't work negative numbers...
Comments
Post a Comment