converting values to hexadecimal for array transmission in JavaScript

Looking to insert a hexadecimal value into an array in order to write to a device via modbus/TCP using socket communication. Currently facing an issue where I am unable to retrieve the hex value with the same data type as the elements present in byteArrayWriteTemperature. After calculating the crc for preparing the array to be sent, it is necessary to add this crc at the end of the array.

For instance, if value = 45, my resulting array would look like:

array = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, 0x2d, 0x23, 0x8d]

When using the Crc16() method on

buff = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, 0x2d]
where the last element is 0x2d (equivalent to decimal value `45`), the generated crc result is swapped = 8d23 rather than 238d as seen in the last 2 elements of array.

setTemperature(value: number) {
    console.log('about to set temperature value ', value);
    let hex = value.toString(16)

    const byteArrayWriteTemperature = [0x01, 0x10, 0x04, 0x00, 0x00, 0x01, 0x02, 0x00, hex];
    let crc = this.Crc16(byteArrayWriteTemperature, byteArrayWriteTemperature.length)
    console.log('crc ', crc)
    console.log('array: ', byteArrayWriteTemperature);
    this.writeToDevice(byteArrayWriteTemperature)
  }

Crc16(buff, length) {
    let crc = 0xffff;

    for (let pos = 0; pos < length; pos++) {
      crc ^= buff[pos]; // (uint8_t)          // XOR byte into least sig. byte of crc

      for (let i = 8; i != 0; i--) {
        // Loop over each bit
        if ((crc & 0x0001) != 0) {
          // If the LSB is set
          crc >>= 1; // Shift right and XOR 0xA001
          crc ^= 0xa001;
        } else {
          crc >>= 1; // Just shift right
        } // Else LSB is not set
      }
    }
    return crc;
  }

Seeking guidance on how to properly format my array. Thank you

Answer №1

Based on my understanding of the question, you are looking to store your crc in little endian order and add it to the end of the array.

So instead of:

return crc;

You should use:

return [crc & 0xFF, (crc & 0xFF00) >> 8];

This will give you an array with values [0x23, 0x8d] if the crc value is 0x8d23.

Following this line:

let crc = this.Crc16(byteArrayWriteTemperature, byteArrayWriteTemperature.length);

Include:

byteArrayWriteTemperature = byteArrayWriteTemperature.concat(crc);

This will append the crc to the end of the byteArrayWriteTemperature array

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to clear a row of images and then repopulate it with new images without losing the click listeners associated with each image?

I am currently developing a memory game that involves clicking on images as the main objective. After clicking on an image, the pictures are then rearranged on the page. However, if you click on the same image twice, you will lose and the game will reset. ...

What other strategies can I utilize to enhance my bundle and boost webpage loading time?

In my React application, I've utilized various libraries like redux, redux-form, react-router, leaflet, react-bootstrap, redux-thunk, and more. The minified bundle size is 531kb, while the vendor file stands at 5.32mb. For bundling and optimization, ...

Tips for sending JSON-formatted data from a route to jQuery

Currently, I am facing a challenge with passing a JSON file retrieved from an API to jQuery. The goal is to implement an infinite scroll functionality using jQuery before displaying it in an EJS file. The issue arises when `res.json(data)` is utilized; ins ...

Angular: Understanding Render Delay Caused by *ngIf and Expression Changes from Filters

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'ngIf: false'. Current value: 'ngIf: true'. Encountering the above error in the console. In my code, I have filters that control ...

PHP-generated AngularJs Select Element

I'm facing an issue with my PHP function in my AngularJS application. I have created a function to select a default option, but it's not displaying the desired value. Here is the function code: function qtyList($selectName, $selectQty){ $st ...

Issue with Global Variable Not Being Updated in Javascript

In my code snippet below, I am struggling to update a global variable within a callback function. function FunctionOne() { var result = ""; for (var i = 0; i < 10; i++) { AjaxFunction(function (data) { result += data; ...

Creating a countdown timer for a specific date and time using web technologies

I'm looking to create a timer countdown that is set to a specific date and time, such as June 1st at midnight. The code should display the remaining time until that date or time. ...

AngularJS UI-Router: Utilizing Optional Parameters

.state('registration', { url:'/app/registration/:ref', templateUrl: 'partials/registration.html', }) This is my configuration for routing using ui-route. It functions properly when I go to localhost:80/r ...

Is it possible for a function parameter to utilize an array method?

Just starting to grasp ES6 and diving into my inaugural React App via an online course. Wanted to share a snag I hit along the way, along with a link to my git repository for any kind souls willing to lend a hand. This app is designed for book organization ...

What steps are involved in setting up a point distribution system in AngularJS?

My objective is to develop a point allocation system within AngularJS. I have successfully created a basic directive that introduces DOM elements, including a span displaying "0" points and buttons for incrementing and decrementing. The total number of poi ...

Utilize JavaScript to seamlessly play a Spotify track within the Spotify client without disrupting your current

A little while back, I recall the simplicity of clicking play on a song within a website and having it instantly start playing on my computer without any additional steps. It was seamless and effortless. My goal for my website is to have music start playi ...

Sending input data without a form

Currently, I am in the process of developing a website game and facing a challenge with implementing a feature I refer to as "dialogue". Initially, I attempted to address this issue by using a form element, but encountered a problem where pressing enter o ...

Tips for extracting only the filename from chokidar instead of the entire file path

I am trying to capture the filename that has been changed, removed, or renamed, but I am currently receiving the full file path. Question: How can I extract only the filename when it is changed, instead of working with the entire file path? This is what ...

Is it possible to store data from a form directly into a MongoDB database?

I am looking to store data collected from an HTML form into a MongoDB database. Below is the code I am using: <!DOCTYPE html> <html> <head> <title>Getting Started with Node and MongoDB</title> </head> <body> ...

In Internet Explorer, the list items are overlapping, while functioning perfectly in all other web browsers

I've encountered a strange issue with my list item in Internet Explorer. Despite working perfectly in Chrome and other browsers, it fails to function properly in IE. I've built this application using the Vue framework and have faced various probl ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

What is the best way to create a reusable component for Cards and implement the new makeStyles feature in material-ui?

Within the depths of my demo.js file, I desire to utilize the Card component with its nested CardHeader and fill in some text within the CardContent. Furthermore, I aim to make the CardComponent easily reusable across multiple files. Any suggestions on how ...

What about connecting mapStateToProps with a specific ID?

Currently, I have a basic function that fetches all Elements const mapStateToProps = ({elements}) => { return { elements: getElementsByKeyName(elements, 'visibleElements'), }; }; I want to modify it to something like this c ...

What steps can I take to ensure that I establish the definition of this variable?

My situation involves a variable called Blog, which is a mongoose model. The definition of this variable is as follows: db.once("open", function(){ var userSchema = new mongoose.Schema({ username: String, password: String }); ...

quickest method for retrieving a property by name, regardless of its location within the object hierarchy

I am looking for a solution to retrieve the value of a property from an object graph, and I am wondering if there is a more efficient alternative to the method I have outlined below. Instead of using recursion, I have chosen tree traversal because it cons ...