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"))