-
-
Save appersiano/ae49eea35e27a29a4aab to your computer and use it in GitHub Desktop.
Convert From/To Binary/Decimal/Hexadecimal in JavaScript + Normalize binary option
This file contains 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
/** | |
* Convert From/To Binary/Decimal/Hexadecimal in JavaScript | |
* https://gist.github.com/faisalman | |
* | |
* Copyright 2012, Faisalman <[email protected]> | |
* Licensed under The MIT License | |
* http://www.opensource.org/licenses/mit-license | |
*/ | |
(function(){ | |
var convertBase = function (num) { | |
this.from = function (baseFrom) { | |
this.to = function (baseTo) { | |
return parseInt(num, baseFrom).toString(baseTo); | |
}; | |
return this; | |
}; | |
return this; | |
}; | |
function normalizeTo(n_bit,binary){ | |
if (binary.length == n_bit) { | |
return binary; | |
} else { | |
var msb = ""; | |
for (var i=0; i<(n_bit - binary.length); i++){ msb = msb+"0"; } | |
return msb+binary; | |
} | |
} | |
// binary to decimal | |
this.bin2dec = function (num) { | |
return convertBase(num).from(2).to(10); | |
}; | |
// binary to hexadecimal | |
this.bin2hex = function (num) { | |
return convertBase(num).from(2).to(16); | |
}; | |
// binary to octal | |
this.bin2oct = function (num) { | |
return convertBase(num).from(2).to(8); | |
}; | |
// decimal to binary | |
this.dec2bin = function (num, n_bit) { | |
if (typeof n_bit === 'undefined'){ | |
return convertBase(num).from(10).to(2); | |
} else { | |
return normalizeTo(n_bit, convertBase(num).from(10).to(2)); | |
} | |
}; | |
// decimal to hexadecimal | |
this.dec2hex = function (num) { | |
return convertBase(num).from(10).to(16); | |
}; | |
// decimal to octal | |
this.dec2octal = function (num) { | |
return convertBase(num).from(10).to(8); | |
}; | |
// hexadecimal to binary | |
this.hex2bin = function (num, n_bit) { | |
if (typeof n_bit === 'undefined'){ | |
return convertBase(num).from(16).to(2); | |
} else { | |
return normalizeTo(n_bit, convertBase(num).from(16).to(2)); | |
} | |
}; | |
// hexadecimal to decimal | |
this.hex2dec = function (num) { | |
return convertBase(num).from(16).to(10); | |
}; | |
// hexadecimal to octal | |
this.hex2dec = function (num) { | |
return convertBase(num).from(16).to(8); | |
}; | |
return this; | |
})(); | |
/* | |
* Usage example: | |
* bin2dec('111'); // '7' | |
* dec2hex('42'); // '2a' | |
* hex2bin('f8'); // '11111000' | |
* dec2bin('22'); // '10110' | |
* dec2bin('3','5'); // '00011' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment