# Modbus crc16 calculation function error syntax

**URL:** <https://discourse.nodered.org/t/modbus-crc16-calculation-function-error-syntax/68657>\
**Category:** General\
**Tags:** function-node\
**Created:** [7 October 2022 06:20 UTC](https://discourse.nodered.org/t/modbus-crc16-calculation-function-error-syntax/68657 "2022-10-07T06:20:03Z")\
**Posts on this page:** 1\
**Showing post:** 6

<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:** [7 October 2022 08:36 UTC](https://discourse.nodered.org/t/modbus-crc16-calculation-function-error-syntax/68657/6 "2022-10-07T08:36:32Z")

</div>

The issue is monaco (trys) to help too much some times.

It is essentially pointing out the code is not great - the function returns a number, then converts to string then it is split to an array of characters. Technically, it works, but it is ugly.

Here is a very quick fix up...

![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/9/1/9143ae7fb90a0d4b3700d628319999429edf2538.png)

```javascript
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;

```

---

_[View the full topic](https://discourse.nodered.org/t/modbus-crc16-calculation-function-error-syntax/68657)._
