Search code examples
javacrccrc16

Java - How to calculate CRC16 of BitSet


I Have a Java BitSet where i have some data. The length of this BitSet is 545 bits. Problem: All current known implementations can only work with a byte array, but converting my BitSet to a byte array will change the data because i need to do some padding. Is there any known implementation which can handly my data without needing to adjust it to whole bytes?


Solution

  • Use .toByteArray() to get the bits into a sequence of bytes. You need to know what CRC-16 definition is required (polynomial, ordering, pre and post processing), and the order in which to process the bits. .toByteArray() will put the first bit in the set in the least-significant bit of the first byte.

    Then you can use crcany to generate C code for the CRC-16 you need. The generated code includes a crc16..._rem() routine for updating the CRC with a number of bits. For a BitSet with n bits, you would first compute the CRC on the first n >> 3 bytes. Then use crc16..._rem() to update the CRC using the n & 7 bits in the last byte. It is straightforward to convert the C code to Java.