# Error in calculation function of crc-16 check code

**URL:** <https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591>\
**Category:** General\
**Created:** [22 February 2023 15:39 UTC](https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591 "2023-02-22T15:39:53Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Angin](https://avatars.discourse-cdn.com/v4/letter/a/eb8c5e/32.png) [@Angin](https://discourse.nodered.org/u/Angin)\
**Post date:** [22 February 2023 15:39 UTC](https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591/1 "2023-02-22T15:39:53Z")

</div>

Hi, Steve-Mcl, sorry to bother you again, I found a bug in your previous function for calculating crc16 that the last two digits of the check code will not be displayed if there are 0's in it, what do I need to do to fix this bug? Thanks again!

![Clipboard 2](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/4/4/447928b603f26e96291e925bb38926e3d619841a.jpeg)

```auto
[
    {
        "id": "12dd6725e2172907",
        "type": "function",
        "z": "434f482843cce883",
        "name": "crc16_buffer",
        "func": "function crc16(str) {\n const buf = Buffer.from(str, 'hex')\n let crc = 0xFFFF;\n for (let i = 0; i < buf.length; i++) {\n crc = crc ^ buf[i];\n for (let j = 0; j < 8; j++) {\n const temp = crc & 0x01;\n crc >>= 0x01;\n if (temp == 0x01) {\n crc ^= 0xA001;\n }\n }\n }\n return crc;\n}\n\nconst crc = crc16(msg.payload);\nconst arr = crc.toString(16).toUpperCase().substring(-4).split(\"\");\nmsg.payload = msg.payload + arr.splice(-2).concat(arr).join(\"\");\nreturn msg;",
        "outputs": 1,
        "noerr": 0,
        "initialize": "",
        "finalize": "",
        "libs": [],
        "x": 1630,
        "y": 1540,
        "wires": [
            [
                "2d38da89494f0166"
            ]
        ]
    },
    {
        "id": "9bf78df919110200",
        "type": "inject",
        "z": "434f482843cce883",
        "name": "",
        "props": [
            {
                "p": "payload"
            },
            {
                "p": "topic",
                "vt": "str"
            }
        ],
        "repeat": "",
        "crontab": "",
        "once": false,
        "onceDelay": 0.1,
        "topic": "",
        "payload": "fe0500010000",
        "payloadType": "str",
        "x": 1450,
        "y": 1540,
        "wires": [
            [
                "12dd6725e2172907"
            ]
        ]
    },
    {
        "id": "2d38da89494f0166",
        "type": "debug",
        "z": "434f482843cce883",
        "name": "debug 11",
        "active": true,
        "tosidebar": true,
        "console": false,
        "tostatus": false,
        "complete": "false",
        "statusVal": "",
        "statusType": "auto",
        "x": 1800,
        "y": 1540,
        "wires": []
    }
]

```

```auto
function crc16(str) {
    const buf = Buffer.from(str, 'hex')
    let crc = 0xFFFF;
    for (let i = 0; i < buf.length; i++) {
        crc = crc ^ buf[i];
        for (let j = 0; j < 8; j++) {
            const temp = crc & 0x01;
            crc >>= 0x01;
            if (temp == 0x01) {
                crc ^= 0xA001;
            }
        }
    }
    return crc;
}

const crc = crc16(msg.payload)
const arr = crc.toString(16).toUpperCase().substring(-4).split("")
msg.payload = msg.payload + arr.splice(-2).concat(arr).join("");
return msg;

```

![Clipboard 1](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/4/b/4b5bc6af162b736fcab4cfa48d1e05d8c75fe519.jpeg)

The correct string should be：fe05000400009804, fe05000100008805

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [23 February 2023 10:32 UTC](https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591/2 "2023-02-23T10:32:48Z")

</div>

> [@Angin](#):
>
> ```auto
> const arr = crc.toString(16).toUpperCase().substring(-4).split("")
> 
> ```

change this line ↑ to this ↓

```auto
const arr = crc.toString(16).padStart(4, '0').toUpperCase().substring(-4).split("")

```

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/f/d/fdf3b58a5eded75483fb222d008434d372a6644d.png)

Working Demo Flow...

```auto
[{"id":"12dd6725e2172907","type":"function","z":"1543d308b342690a","name":"crc16_buffer","func":"function crc16(str) {\n const buf = Buffer.from(str, 'hex')\n let crc = 0xFFFF;\n for (let i = 0; i < buf.length; i++) {\n crc = crc ^ buf[i];\n for (let j = 0; j < 8; j++) {\n const temp = crc & 0x01;\n crc >>= 0x01;\n if (temp == 0x01) {\n crc ^= 0xA001;\n }\n }\n }\n return crc;\n}\n\nconst crc = crc16(msg.payload);\nconst arr = crc.toString(16).padStart(4, '0').toUpperCase().substring(-4).split(\"\");\nmsg.payload = msg.payload + arr.splice(-2).concat(arr).join(\"\");\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":1350,"y":760,"wires":[["2d38da89494f0166"]]},{"id":"9bf78df919110200","type":"inject","z":"1543d308b342690a","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"fe0500010000","payloadType":"str","x":1170,"y":780,"wires":[["12dd6725e2172907"]]},{"id":"2d38da89494f0166","type":"debug","z":"1543d308b342690a","name":"debug 11","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":1520,"y":760,"wires":[]},{"id":"65395e103f7f3d4d","type":"inject","z":"1543d308b342690a","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"fe0500040000","payloadType":"str","x":1170,"y":740,"wires":[["12dd6725e2172907"]]}]

```

---

<div class="post-metadata">

**Author:** ![Angin](https://avatars.discourse-cdn.com/v4/letter/a/eb8c5e/32.png) [@Angin](https://discourse.nodered.org/u/Angin)\
**Post date:** [23 February 2023 10:48 UTC](https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591/3 "2023-02-23T10:48:30Z")

</div>

After testing, the results have been completely correct, thanks again for your selfless help!

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [9 March 2023 10:49 UTC](https://discourse.nodered.org/t/error-in-calculation-function-of-crc-16-check-code/75591/4 "2023-03-09T10:49:07Z")

</div>

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.
