Issue with formatting and hexadecimal encoding in JavaScript

I am currently developing a LoRaWAN encoder using JavaScript. The data field received looks like this:

{“header”: 6,“sunrise”: -30,“sunset”: 30,“lat”: 65.500226,“long”: 24.833547}

My task is to encode this data into a hex message. Below is the code I have so far:

var header = byteToHex(object.header);
var sunrise =byteToHex(object.sunrise);
var sunset = byteToHex(object.sunset);
var la = parseInt(object.lat100,10);
var lat = swap16(la);
var lo = parseInt(object.long100,10);
var lon = swap16(lo);
var message={};
if (object.header === 6){
    message = (lon)|(lat<<8);
    bytes = message;
}
return hexToBytes(bytes.toString(16));

The functions byteToHex / swap16 are defined as follows:

function byteToHex(byte) {
    var unsignedByte = byte & 0xff;
    if (unsignedByte < 16) {
        return ‘0’ + unsignedByte.toString(16);
    } else {
        return unsignedByte.toString(16);
    }
}

function swap16(val) {
    return ((val & 0xFF) << 8) | ((val >> 8) & 0xFF);
}

When testing with return message = lon, I get B3 09 in hex. However, when testing with message = lon | lat <<8, I get 96 BB 09 instead of the desired result 96 19 B3 09 (combining lon + lat).

Any advice on what may be going wrong?

Answer №1

This problem was successfully resolved by utilizing the following code:

    // Extracting latitude and longitude from object
    var long = object.long;
    var lat = object.lat;

    // Converting latitude to a 16-bit signed integer
    lat = parseInt(lat * 100, 10);
    var la = swap16(lat);
    la = la.toString(16);

    // Converting longitude to a 16-bit signed integer
    long = parseInt(long * 100, 10);
    var lon = swap16(long);
    lon = lon.toString(16);

    // Obtaining the header information from the object
    var header = object.header;

    // Combining latitude and longitude into a single result variable
    var result = la;
    result += lon;

    // Converting the combined result to hexadecimal format
    result = result.toString(16);

    // Converting the hexadecimal result to bytes
    bytes = hexToBytes(result);

The current response is as follows:

// encoded payload:
96 19 B3 09

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

Maintaining the consistent structure of build directories within a Docker container is crucial, especially when compiling TypeScript code that excludes the test

Our application is built using TypeScript and the source code resides in the /src directory. We have tests located in the /tests directory. When we compile the code locally using TSC, the compiled files are deposited into /dist/src and /dist/test respectiv ...

When attempting to execute a promise within a test, encountering a 400 error in a NodeJS environment

I recently started using Contentful, a new JavaScript library for creating static websites. My goal is to incorporate it into my Node.js project. To achieve this, I developed an app file called getContent.js: 'use strict'; var contentful = req ...

Develop a unique Kotlin/JS WebComponent featuring custom content

I am trying to create a custom tag using Kotlin that includes default content. While the example I found works well, I am having trouble adding default content (such as an input element) inside the custom tag. After attempting various approaches, I have o ...

Is there a way to retrieve the previous value in an input field's onChange event?

I am working with inputs in a React project and have assigned a function to their onChange event. While I have been able to access the current value, I am now looking for a way to retrieve the previous value as well. The reason I need the old value is bec ...

Issues with the Content Editable Functionality

While working on my website, I encountered a strange issue. For some reason, I can't seem to get the contenteditable="true" attribute to work on the heading with the ID "hl". It would be awesome if someone could help me figure out how to mak ...

Setting the rotation position in JQuery prior to initiating the animation

Perhaps I could phrase my query differently as How can I rotate an image in JQuery from a starting position other than 0 degrees. I am attempting to animate the rotation of an image from -50deg to 0deg. However, regardless of what I do, JQuery seems to al ...

collection of assurances and the Promise.all() method

Currently, I am dealing with an array of Promises that looks like this: let promisesArray = [ service1.load('blabla'), service2.load(), // throws an error ]; My goal is to execute all these Promises and handle any errors that occur, as ...

Identify when an ajax request is completed in order to trigger a subsequent ajax request

Within my project, I am faced with a challenge involving select option groups that dynamically load ajax data based on previous selections. The issue arises when I attempt to replicate this functionality for another select option group. Here is the scenar ...

Issues arise when Angular properties become undefined following the initialization or OnInit functions

There seems to be a peculiar issue with the properties of an angular component that I have set up. It appears that these properties are losing their values after the initialization process. The component is essentially a basic HTML file containing a video ...

Transform XML data into JSON format including arrays using WSO2

Looking to transform XML data into JSON format with XSLT, I noticed that when there is only a single node in the XML, the resulting JSON does not include an array. However, if there are multiple nodes present, they are displayed as an array. For example, ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...

Tips for inputting information without redundancy after selecting a specific designation

I'm experiencing a challenge with this code as it repeats when already chosen. My goal is to add data in the database once something has been selected. When I click on spin, the randomizer will choose a name and update their status to "done". Subsequ ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

Processing JSON in PHP to retrieve data

I'm trying to figure out how to parse JSON data using PHP. Here is a basic example: $myJSON_string = '{ "features": [{ "type": "Feature", "geometry": { "type": "Point", "coordinates": ...

When you add a new library using npm and it has a dependency on another existing library, it could potentially cause conflicts or issues with

After successfully installing a library, I am now looking to install another library that relies on the first one. I have some uncertainty about what will occur: The second library will utilize the shared library already installed for its functionality ...

Identifying when several asynchronous JavaScript $.ajax requests have finished

I have a JavaScript function that runs a loop and makes asynchronous AJAX calls. I need to wait for all the AJAX calls to complete before updating the UI. Here is the loop: function sync_SyncLocalStorageToServer() { if (helper_IsAppOnline()) { ...

Is it possible to define key strings as immutable variables in JavaScript/Node.js?

Having transitioned from the world of Java to working with Node.js + AngularJS for my current project, I have encountered a dilemma. There are certain "key Strings" that are used frequently in both client and server-side code. In Java, it is common practi ...

Master the Art of Transforming an Array into a Variable

Here is an example of an array: const [listArr, setLA]= useState([ { id: Math.floor(Math.random * 100000), data: "This is data 1", }, { id: Math.floor(Math.random * 100000), data: "This is data 2", ...

What is the best way to open the index.html file in electron?

I'm currently developing a cross-platform app using electron and Angular. As of now, the code I have for loading my index.html file looks like this: exports.window = function window() { this.createWindow = (theBrowserWindow) => { // Create ...