Skip to content

Instantly share code, notes, and snippets.

@appersiano
Forked from gpedro/baseConverter.js
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save appersiano/ae49eea35e27a29a4aab to your computer and use it in GitHub Desktop.
Save appersiano/ae49eea35e27a29a4aab to your computer and use it in GitHub Desktop.
Convert From/To Binary/Decimal/Hexadecimal in JavaScript + Normalize binary option
/**
* Convert From/To Binary/Decimal/Hexadecimal in JavaScript
* https://gist.github.com/faisalman
*
* Copyright 2012, Faisalman <fyzlman@gmail.com>
* 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