@jorge-gonzalez said in Script to convert from Hex to Dec:
13:32
@Jorge-Gonzalez, documentation to solve your problems.
Firstly see what parseInt does - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
There you can see that the hexdecimal value has to be in correct format be it with 0x or without. Your string splits 2 bytes in the hexdecimal format by using a colon. You need to remove it. Simply do it by utilizing .replace method on a string before putting it into parseInt. Or if you have a string which contains multiple values utilize .split method on a string and then put the bytes together before putting the value into parseInt.
Replace method explanation
https://www.w3schools.com/jsref/jsref_replace.asp
Split method explanation
https://www.w3schools.com/jsref/jsref_split.asp
Following function is following the detailed explanation you provided in the post.
function stringsplitter (string) { var result = {}; // This contains the bytes of data result.arrayofbytes = string.split(':'); // Get byte count of data inside the string result.bytecount = result.arrayofbytes.length; // Start at the beginning var variablecounter = 0; result.hexdata = []; result.decimaldata = []; // Loop over the array, but taking into account that we have 2 byte data, use try/catch so that function will return if something should fail try{ for (var x = 0;x < result.bytecount / 2;x++){ result.hexdata[x] = result.arrayofbytes[variablecounter] + result.arrayofbytes[variablecounter+1]; result.decimaldata[x] = parseInt(result.hexdata[x],16); variablecounter += 2; } }catch(err){ return err } // return object with all our data which includes hexdecimal data, decimaldata and byte count inside the string return result; } // Example usage var devicestring = '13:30:27:14:01:33:02:6c:02:76'; var data = stringsplitter(devicestring); //get array in hexdecimal and decimal format var hexdata = data.hexdata; var decimaldata = data.decimaldata; // first value in hexdecimal and decimal format var firstvaluehex = hexdata[0]; var firstvaluedecimal = decimaldata[0]; // Second value in hexdecimal and decimal format var secondvaluehex = hexdata[1]; var secondvaluedecimal = decimaldata[1]; // Following that your post had used an example with the last value var lastvalue = decimaldata[4]; // Should be 23 var lastvaluecorrected = lastvalue * 0.1 - 40;Thomas