-
-
Save DragonI/989d0dd4ae5089fb1e3a03e0f7fd151d to your computer and use it in GitHub Desktop.
ES6: Convert From/To Binary/Decimal/Hexadecimal in JavaScript
This file contains hidden or 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-2015, Faisalman <[email protected]> | |
* Licensed under The MIT License | |
* http://www.opensource.org/licenses/mit-license | |
* | |
* 6/20/2016 - DragonI | |
* Hipsterize faisalman's excellent code to ES6 | |
*/ | |
const BINARY = 2 | |
const DECIMAL = 10 | |
const HEX = 16 | |
const ConvertBase = num => ({ | |
from: (baseFrom) => { | |
return { | |
to: (baseTo) => { | |
return parseInt(num, baseFrom).toString(baseTo) | |
} | |
} | |
} | |
}) | |
// binary to decimal | |
export function bin2dec (num) { | |
return ConvertBase(num).from(BINARY).to(DECIMAL) | |
} | |
// binary to hexadecimal | |
export function bin2hex (num) { | |
return ConvertBase(num).from(BINARY).to(HEX) | |
} | |
// decimal to binary | |
export function dec2bin (num) { | |
return ConvertBase(num).from(DECIMAL).to(BINARY) | |
} | |
// decimal to hexadecimal | |
export function dec2hex (num) { | |
return ConvertBase(num).from(DECIMAL).to(HEX) | |
} | |
// hexadecimal to binary | |
export function hex2bin (num) { | |
return ConvertBase(num).from(HEX).to(BINARY) | |
} | |
// hexadecimal to decimal | |
export function hex2dec (num) { | |
return ConvertBase(num).from(HEX).to(DECIMAL) | |
} | |
/* | |
* Usage example: | |
* import {bin2dec, dec2hex, hex2bin, dec2bin} from './baseConverter' | |
* | |
* bin2dec('111') // '7' | |
* dec2hex('42') // '2a' | |
* hex2bin('f8') // '11111000' | |
* dec2bin('22') // '10110' | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here's an example on WebpackBin. Check the console for the results