Skip to content

Instantly share code, notes, and snippets.

@dan-zheng
Forked from faisalman/baseConverter.js
Created October 22, 2016 03:22
Show Gist options
  • Select an option

  • Save dan-zheng/cde914409b460f5991c5f8dbb59ae4b4 to your computer and use it in GitHub Desktop.

Select an option

Save dan-zheng/cde914409b460f5991c5f8dbb59ae4b4 to your computer and use it in GitHub Desktop.
Convert From/To Binary/Decimal/Hexadecimal in JavaScript
/**
* 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
*/
var convertBase = function (num) {
this.from = function (baseFrom) {
this.to = function (baseTo) {
return parseInt(num, baseFrom).toString(baseTo);
};
return this;
};
return this;
},
// binary to decimal
bin2dec = function (num) {
return convertBase(num).from(2).to(10);
},
// binary to hexadecimal
bin2hex = function (num) {
return convertBase(num).from(2).to(16);
},
// decimal to binary
dec2bin = function (num) {
return convertBase(num).from(10).to(2);
},
// decimal to hexadecimal
dec2hex = function (num) {
return convertBase(num).from(10).to(16);
},
// hexadecimal to binary
hex2bin = function (num) {
return convertBase(num).from(16).to(2);
},
// hexadecimal to decimal
hex2dec = function (num) {
return convertBase(num).from(16).to(10);
};
/*
* Usage example:
* bin2dec('111'); // '7'
* dec2hex('42'); // '2a'
* hex2bin('f8'); // '11111000'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment