Search code examples
javascriptcrc

Calculate reverse polynomial for given polynomial for calculating CRC


I am writing a javascript code for calculating the reverse polynomial from given generator polynomial but there seems to be some error it works great for few CRC method (CRC-8, CRC-16, CRC-CCITT, CRC-32, CRC-32C) but not for all of them .. please point out where i am going wrong.

<input type="text" name="poly" id="poly" onkeyup="getRevPoly()">
<input type="text" name="rpoly" id="rpoly" disabled>

<script type="text/javascript">
function getRevPoly() {
  var poly = document.getElementById('poly').value;
  var bin = convertBase(poly, 16, 2);
  bin = pad(bin, (poly.length));
  bin = bin.split('').reverse().join('');
  var hex2 = convertBase(bin, 2, 16);
  document.getElementById('rpoly').value = hex2.toUpperCase();
}
function convertBase(num, baseA, baseB) {
          return parseInt(num, baseA).toString(baseB);
}

function pad(num, size) {
      var s = num;
      while (s.length < (size * 4)) s = "0" + s;
      return s;
}
</script>

Solution

  • That code will only work for CRCs with lengths that are a multiple of four bits. So it won't work for the CRC-5s you (finally) mention in the comments to your question. In fact, there is no code that can take a hexadecimal representation of a polynomial sans the high term and magically deduce the number of bits. You need another input which is the number of bits in the CRC.