Created
May 22, 2018 17:16
-
-
Save patrickjmcd/40e7ca1cff75dedb5806f321e0c6d2b0 to your computer and use it in GitHub Desktop.
Converts Modbus Register Integers into Siemens TotalType data type
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function toTotalType(number_1, number_2, decimal_1, decimal_2){ | |
const number = (makeTwosComplement32BitInt( | |
numberTo16BitBinary(number_1), | |
numberTo16BitBinary(number_2) | |
)); | |
const decimal = (makeTwosComplement32BitInt( | |
numberTo16BitBinary(decimal_1), | |
numberTo16BitBinary(decimal_2) | |
)); | |
return number + decimal / 1000000000 | |
} | |
function numberTo16BitBinary(num){ | |
const binString = ("0".repeat(16) + num.toString(2)).slice(-16); | |
return binString; | |
} | |
function binary16BitToNumber(binRep){ | |
const intRep = parseInt(binRep, 2); | |
return intRep; | |
} | |
function makeBinaryStringFrom32BitInt(intVal){ | |
const bin32 = ("0".repeat(32) + intVal.toString(2)).slice(-32); | |
return [ bin32.substr(0,16), bin32.substr(16,16) ] | |
} | |
function makeTwosComplement32BitInt(high, low){ | |
const combined = high + low; | |
let intVal = parseInt(combined, 2); | |
if (high[0] === "1"){ | |
let twosString = []; | |
for(let bit in combined){ | |
const newBit = combined[bit] === "0" ? 1 : 0; | |
twosString.push(newBit) | |
} | |
intVal = -1 * (parseInt(twosString.join(""), 2) + 1); | |
} | |
return intVal; | |
} | |
console.log(toTotalType(65535, 65534, 4577, 41728)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment