(String message)
| 12 | } |
| 13 | |
| 14 | public static String crc16(String message) { |
| 15 | int crc = 0xFFFF; // initial value |
| 16 | int polynomial = 0x1021; // 0001 0000 0010 0001 (0, 5, 12) |
| 17 | byte[] bytes = message.getBytes(); |
| 18 | |
| 19 | for (byte b : bytes) { |
| 20 | for (int i = 0; i < 8; i++) { |
| 21 | boolean bit = ((b >> (7 - i) & 1) == 1); |
| 22 | boolean c15 = ((crc >> 15 & 1) == 1); |
| 23 | crc <<= 1; |
| 24 | if (c15 ^ bit) { |
| 25 | crc ^= polynomial; |
| 26 | } |
| 27 | } |
| 28 | } |
| 29 | crc &= 0xffff; |
| 30 | return Integer.toHexString(crc).toUpperCase(); |
| 31 | } |
| 32 | } |