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

"Two vibrant hues in a showdown for dominance over a single pixel on the screen in

When using this Three.js application (), the issue arises where the black wireframe competes with the yellow solid, causing pixel flickering on the screen. Is there a way to prevent this from happening? It's worth noting that the flickering effect is ...

In my Angular application, I have two div elements that I want to toggle between. When a button located in the first div is clicked, I need

I am working on a code snippet that requires me to hide div1 and display div2 when the button in div1 is clicked using Angular HTML5. Currently, I have two separate modal pop up template files and JS controllers for each of them. Instead of having two po ...

Strange symbols keep appearing in my output from PHP

My current task involves generating a SQL query based on some inputs. I have a predefined SQL statement, in which I perform certain replacements, that will use these inputs to generate the required SQL through an ODBC connection. For now, I have stored th ...

Navigate to the AngularJS documentation and locate the section on monitoring data changes after a dropdown selection

Just starting out with AngularJS and Stack Overflow, so I hope I am asking this question correctly. I am working on a single-page application with editable text inputs. Two select drop-downs are used to control which data is displayed - one for time perio ...

Navigate through content easily using the arrow keys on your keyboard with the help of Easy Slider

I'm attempting to modify the Easy Slider in order to enable navigation of the slideshow with the arrow keys on the keyboard. I made adjustments to the javascript's animate function, changing it from: default: t = dir; break; ...to: default: t ...

Is it possible for a lambda in TypeScript to have access to the class scope but return undefined

In my TypeScript code, I have a class used as a Pipe in Angular 2 to render markdown. It compiles successfully but encounters a runtime exception on a specific line: var Remarkable = require('remarkable'); @Pipe({ name: 'markdown' ...

Exploring alternative methods of iterating over the values in a key-value pair within an AngularJS framework

My key-value pair consists of a long list of file names stored in the variable $ctrl.displayData- 143:"/this/is/a/very/long/fil22↵/this/is/a/very/long/file/path.php↵anotherone.php↵newfilel123.php" When I use ng-repeat to display these file names, t ...

The Bootstrap modal form fails to properly handle the POST method when sending data to the server

I am encountering an issue with a button that triggers a modal form <a href="#" class="btn btn-primary" data-toggle="modal" data-target="#agregarProducto">Add Material</a> The modal appears as shown below: https://i.stack.imgur.com/J39x9.pn ...

When incorporating Request.js and Cheerio.js into Node/Express, an unexpected outcome may occur where an empty

I am currently in the process of creating a basic web scraper using Request.js and Cheerio.js within Express. My main goal at the moment is to extract the titles of various websites. Instead of scraping each website individually, I have compiled them int ...

What is the best way to eliminate the "0"s from the center of items within an array?

I have developed a table sorter that handles columns containing both letters and numbers, such as "thing 027". To facilitate sorting, I prepended zeros to the numbers. However, I am now looking for a cleaner way to remove these zeros from the numbers using ...

Looking for repeating values in inputs excluding this one

In the midst of a medium-sized project, an issue has arisen. I have condensed the core problem into this code snippet. Here's what the code does: $(".6").focusout(function(){ if( $(".6").filter(function(){ return this.value;}).not(this).length>0 ...

Utilize AngularJS to integrate a service into the router functionality

What is the best way to inject a service into my router so that its JSON result will be accessible throughout the entire application? Router: export default ['$stateProvider', '$urlRouterProvider', function($stateProvider, $urlRouterP ...

Striped artifacts can be observed in the lights of A-Frame technology, with their appearance varying depending

I'm currently using A-Frame version 1.0.4 and have experimented with both spotlights (as shown in the attached image) and direct light sources. Adjusting the shadowBias to -0.0001 only minimally impacts the artifact issue. By setting shadowMapHeight ...

Strip newline characters from information in AngularJS

What is the recommended approach for detecting and formatting the "\n\n" line breaks within text received from the server before displaying it? Check out this Fiddle: http://jsfiddle.net/nicktest2222/2vYBn/ $scope.data = [{ terms: 'You ...

Rest Sharp doesn't support serializing dates

Is the default setting in the latest Restsharp supposed to be able to serialize a `Datetime`? Here is how I am building my request: var request = new RestRequest(Method.POST); request.RequestFormat = DataFormat.Json; //request.JsonSerializer = new MyJson ...

What is the best way to upload my React project to GitHub without adding the node modules directory?

I'm looking to share my React Project on GitHub, but I don't want to include the node modules folder. What's the best way to go about this? ...

Modify the value of a variable every 250 milliseconds

Currently working on a game website and stuck at the registration stage. We are looking to allow players to input a code in their Ingame notes for verification purposes. I have created a PHP class to retrieve the ingame notes, but now I need to set a java ...

The inheritance caused this scope to be lost

Here is an illustration of code with two files and "classes". In the CRUD class, there is a problem with this.modelName when setting routes as it changes the context. The question arises on how to maintain the same scope within the CRUD where modelName is ...

Call a React component from an external JavaScript file

I am working on a react application that has a bundle.js file created using webpack containing all the necessary code. Recently, I started developing a separate dotnet application and I need to display the main 'App' component from my react appl ...

Issues with sending empty strings to an API in Vue Js

My code below is designed to update data using a Node Js REST API. The remaining field contains an equation using v-model=remaininginst to calculate and store the result in remaininginst. However, when I check the console.log, I am getting NaN empty data s ...