The ~ in the original code only worked because it was a 16-bit type. You should use crcX = crcX ^ 0xffff instead of crcX = ~crcX.
Also your buf.substring(i,i+4) and i = i + 4 is wrong. You need to process one byte at a time, which is two hexadecimal digits. Those should both be i+2.