Last active
May 14, 2018 21:20
-
-
Save shamshul2007/80ff452954ca1c5ef88461974a07bbbf to your computer and use it in GitHub Desktop.
Convert numbers between different bases, such as hexadecimal and decimal in JavaScript
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/shamshul2007/ | |
* Copyright 2012-2015, Shamshul <shamshul2007@gmail.com> | |
* Licensed under The MIT License | |
* http://www.opensource.org/licenses/mit-license | |
*/ | |
(function(){ | |
var ConvertBase = function (num) { | |
return { | |
from : function (baseFrom) { | |
return { | |
to : function (baseTo) { | |
return parseInt(num, baseFrom).toString(baseTo); | |
} | |
}; | |
} | |
}; | |
}; | |
// binary to decimal | |
ConvertBase.bin2dec = function (num) { | |
return ConvertBase(num).from(2).to(10); | |
}; | |
// binary to hexadecimal | |
ConvertBase.bin2hex = function (num) { | |
return ConvertBase(num).from(2).to(16); | |
}; | |
// decimal to binary | |
ConvertBase.dec2bin = function (num) { | |
return ConvertBase(num).from(10).to(2); | |
}; | |
// decimal to hexadecimal | |
ConvertBase.dec2hex = function (num) { | |
return ConvertBase(num).from(10).to(16); | |
}; | |
// hexadecimal to binary | |
ConvertBase.hex2bin = function (num) { | |
return ConvertBase(num).from(16).to(2); | |
}; | |
// hexadecimal to decimal | |
ConvertBase.hex2dec = function (num) { | |
return ConvertBase(num).from(16).to(10); | |
}; | |
//Octal to Decimal | |
ConvertBase.oct2dec = function (num) { | |
return ConvertBase(num).from(8).to(10); | |
}; | |
//Decimal to Octal | |
ConvertBase.dec2oct = function (num) { | |
return ConvertBase(num).from(10).to(8); | |
}; | |
this.ConvertBase = ConvertBase; | |
})(this); | |
/* | |
* Usage example: | |
* ConvertBase.bin2dec('1111'); // '15' | |
* ConvertBase.dec2hex('82'); // '52' | |
* ConvertBase.hex2bin('e2'); // '11100010' | |
* ConvertBase.dec2bin('153'); // '10011001' | |
* ConvertBase.hex2dec('1FE4ED63D55FA51E'); //'2298222722903156000' | |
* ConvertBase.oct2dec('777'); //'511' | |
* ConvertBase.dec2oct('551'); //'1047' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment