Program hex2bin in javascript - Node.js Number

Node.js examples for Number:Hex

Description

Program hex2bin in javascript

Demo Code


// http://stackoverflow.com/questions/7695450/how-to-program-hex2bin-in-javascript
function checkBin(n){return/^[01]+$/.test(n)}
function checkDec(n){return/^[0-9]+$/.test(n)}
function checkHex(n){return/^[0-9A-Fa-f]+$/.test(n)}
function pad(s,z){s=""+s;return s.length<z?pad("0"+s,z):s}
function unpad(s){s=""+s;return s.replace(/^0+/,'')}

function Dec2Bin(n){if(!checkDec(n)||n<0)return 0;return pad(n.toString(2),8)}
function Dec2Hex(n){if(!checkDec(n)||n<0)return 0;return n.toString(16)}
function Bin2Dec(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(10)}
function Bin2Hex(n){if(!checkBin(n))return 0;return parseInt(n,2).toString(16)}
function Hex2Bin(n){if(!checkHex(n))return 0;return pad(parseInt(n,16).toString(2),8)}
function Hex2Dec(n){if(!checkHex(n))return 0;return parseInt(n,16).toString(10)}

Related Tutorials