Converting time to hexadecimal format then reversing it as a byte array

I've been struggling since yesterday to figure out the reverse of a formula related to working with the HART (Highway Addressable Remote Transducer) Protocol. According to the specification, a constant-expression must resolve to an unsigned 4-byte or 8-byte integer for the DEFAULT_VALUE. For example, encoding a 4-byte TIME_VALUE for 05:14:26 results in DEFAULT_VALUE = ((5*60+14)*60+26)*32000, which equals 603712000 and converts to byte array as 23 FB EA 00.

Now, I need help finding the reverse formula. For instance, converting 444800000 to byte array should result in ‭1A 83 1C 00. By dividing this number by 32000, we get 13900, which ideally should be transformed into a readable time format like hh:mm:ss.

Although I created some functions, they don't seem to work as expected:

secondsPassedToTime = function (seconds) {

    var decimalTime = seconds / 86400;
    var hour = decimalTime * 24;
    var minutes = (hour % 1) * 60 
    var seconds = (minutes % 1) * 60

    hour = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString(); 
    minutes = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
    seconds = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();

    var time = hour.toString() + ":" + minutes.toString() + ":" + seconds.toString();
    return time;
};
console.log(secondsPassedToTime(13900))

Even though this function yields a possible readable format, when turned into a byte array, it does not match the expected value. Instead of 1a 83 1c 00, it becomes 1A 82 9F 00. It seems one of these functions is malfunctioning:

timeToHartTimeByteArray = function (time) {

    var byteArray = new Array();
    var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
    if (time.match(regex)) {
        time = time;
    }
    else {
        throw "Invalid format for TIME! Format must be: hh:mm:ss";
    }
    var time = time.split(":");
    var hours = parseFloat(time[0]) * 3600;
    var minutes = parseFloat(time[1]) * 60;
    var seconds = parseFloat(time[2]);
    var finalTime = hours + minutes + seconds;

    finalTime = finalTime * 32000;

    var hexTime = finalTime.toString(16)

    if (hexTime.length != 8) {
        var hexTime = "0" + hexTime;
        byteArray.push(hexTime.slice(0, 2))
        byteArray.push(hexTime.slice(2, 4))
        byteArray.push(hexTime.slice(4, 6))
        byteArray.push(hexTime.slice(6, 8))
    }
    else {
        byteArray.push(hexTime.slice(0, 2))
        byteArray.push(hexTime.slice(2, 4))
        byteArray.push(hexTime.slice(4, 6))
        byteArray.push(hexTime.slice(6, 8)
    }
    return byteArray;

};

console.log(timeToHartTimeByteArray("03:51:39"))

Answer №1

After some investigation, I identified the issue within the first function where the calculation was completely incorrect:

timeConversion = function (seconds) {
    var hour = seconds * 0.00027778;
    var hh = (~~hour).toString().length < 2 ? "0" + (~~hour).toString() : (~~hour).toString();
    var minutes = (hour - hh) * 60.000;
    var mm = (~~minutes).toString().length < 2 ? "0" + (~~minutes).toString() : (~~minutes).toString();
    var seconds = (minutes - mm) / 0.016667;
    var ss = (~~seconds).toString().length < 2 ? "0" + (~~seconds).toString() : (~~seconds).toString();
    
    return (hh + ":" + mm + ":" + ss)
};
console.log(timeConversion(13900))

Upon correcting the first function, the second function now successfully converts to the accurate hexadecimal value:

convertTimeToHexByteArray = function (time) {

    var byteArray = new Array();
    var regex = /^[0-9]{2}\:[0-9]{2}\:[0-9]{2}/;
    if (time.match(regex)) {
        time = time;
    }
    else {
        throw "Invalid format for TIME! Format must be: hh:mm:ss";
    }
    var time = time.split(":");
    var hours = parseFloat(time[0]) * 3600;
    var minutes = parseFloat(time[1]) * 60;
    var seconds = parseFloat(time[2]);
    var finalTime = hours + minutes + seconds;

    finalTime = finalTime * 32000;

    var hexTime = finalTime.toString(16)

    if (hexTime.length != 8) {
        var hexTime = "0" + hexTime;
        byteArray.push(hexTime.slice(0, 2))
        byteArray.push(hexTime.slice(2, 4))
        byteArray.push(hexTime.slice(4, 6))
        byteArray.push(hexTime.slice(6, 8))
    }
    else {
        byteArray.push(hexTime.slice(0, 2))
        byteArray.push(hexTime.slice(2, 4))
        byteArray.push(hexTime.slice(4, 6))
        byteArray.push(hexTime.slice(6, 8))
    }
    return byteArray;

};

console.log(convertTimeToHexByteArray("03:51:40"))

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

Struggling with the alignment of pictures inside a container

I utilized the Instafeed.js library to fetch the three most recent images from an Instagram account. These images are loaded into a specific div and I successfully customized their styling according to my requirements. However, the current setup is quite s ...

Filter mongoose array to show only the selected ids

I am trying to filter users based on a specific role ID from my user schema. const users = await User.find( { roles: { $in: [params.role] } }, "-password" ) .populate({ path: "roles", }); Below is the structure of my user s ...

Issues with Angular radio buttons are causing them to not be selected properly

When it comes to radio buttons, they should be checked based on certain conditions. <input data-ng-checked="user.contract1 || user.contract2" data-ng-model="user.agreed" type="radio" data-ng-value="true"> Yes <input data-ng-checked="!user.contrac ...

Tips on creating a slow and gradual border animation that unfolds smoothly

I am looking to create an animation effect on a border, gradually revealing it like in this Codepen example. However, my specific requirements are: The previous line should not be removed, but rather shown along with the new border. The border color ...

Guide to submitting a form (adding a new subscriber) using mailchimp-api-v3 with Node.js

I am currently utilizing the mailchimp-api-v3 for form submission purposes. The form I am working with consists of only three fields: FNAME, EMAIL, and COMPANY. const Mailchimp = require('mailchimp-api-v3'); const mailchimp = new Mailchimp(myMa ...

Arranging a collection of structures in C++

For my game, I am utilizing a particle physics library implemented in c++. To render the particles on screen, I need to retrieve an array of their positions using the following code: b2Vec2* particlePositionBuffer = world->GetParticlePositionBuffer(); ...

What is the process for the event loop moving into the poll phase?

There is a scenario outlined in the event loop explanation on the Node.js official website. When setTimeout is triggered, and the callback queue for the timer phase isn't empty, why does the event loop move on to the poll phase? The site mentions that ...

Creating a perpetual loop animation for two divs moving from right to left endlessly

Here is the code I have: HTML <div class="screen screen1"></div> <div class="screen screen2"></div> CSS .screen{ width: 100%; height: 50%; position: absolute; background-color:#001; background-image: radial- ...

Is it possible to restrict the movement of the dialog to stay within the boundaries of the window

html: <div id="dialog" title="Past Issues"> </div> Jquery: $( "#dialog" ).dialog({ height: 900, width:1200, modal: true, }); Currently facing an issue where the dialog can be dragged outside of the window are ...

"Customizing the error handling in jQuery Ajax using the fail method

I attempted to customize the fail method like shown below, however it ends up triggering both fail methods. As a result, I see 2 alerts: "alert 1" and "override fail". Is there a way to only display the alert "override fail"? var jqxhr = $.ajax("exam ...

Having trouble with jQuery live clock freezing your browser?

I recently created a clock script and utilized setInterval to keep it running smoothly. However, I've encountered an issue where my browser freezes after a short period of time. Unfortunately, I'm unsure how to troubleshoot this problem on my own ...

JavaScript's version of "a certain phrase within a text"

If I'm working in Python and need to verify if a certain value is present in a string, I would use: if "bar" in someString: ... What would be the equivalent code in Javascript for this task? ...

Using loop to pass multiple values from a dictionary into a method

Question about incorporating dictionary keys and values into a method using a loop I had an idea to write this code, but it doesn't work as expected because it generates a packet with only one key/value pair each time. for key in packetData: for ...

How can I detect the scroll action on a Select2 dropdown?

Is there a way to capture the scrolling event for an HTML element that is using Select2? I need to be able to dynamically add options to my dropdown when it scrolls. Just so you know: I am using jQuery, and the dropdown is implemented with Select2. The ...

Angular component experiencing difficulty sorting a column sent from parent component to child component

I'm currently facing an obstacle while trying to pass a column from a parent component to a child component in Angular. The issue arises when attempting to sort the column. Below is the code snippet: Parent component <table-sorting-example matSort ...

Navigating with Express and Vue

Currently, I am working on a basic web page that has an index '/' and a 404 page to handle errors at '/404'. In my express app setup, I have the following configuration: // Entry Point app.use("/", express.static(resolve(__di ...

Navigating the ins and outs of utilizing 2D arrays in C

I am relatively new to C programming and I am struggling with understanding pointers in the context of a 2D array. Specifically, I have a 3x3 integer array that I am working with. Here is the method I am currently trying to implement: void addMoveToBoar ...

What is causing the Denial of Service in react-svg-loader version 3.03 - Could it be related to css-what

An issue has been identified with React solution, showing a high vulnerability in npm-audit. The vulnerability is related to Denial of Service in react-svg-loader version 3.03 due to css-what. What potential solutions exist for this issue? Specific detai ...

Internet Explorer experiencing issues with window resizing event

One common issue with Internet Explorer is that the window.resize event is triggered whenever any element on the page is resized. It doesn't matter how the element's size changes, whether it's through height or style attribute modification, ...

Tips for sending information to PrimeVue MenuItems

My PrimeVue Menu setup looks like this: <template> <div class=""> <label class="text-slate-500 text-sm">Doctor Name</label> <div class="text-sm">{{ appointment.doctor.name }}</div> ...