Skip to content

Instantly share code, notes, and snippets.

@DragonI
Forked from faisalman/baseConverter.js
Last active June 21, 2016 15:08
Show Gist options
  • Save DragonI/989d0dd4ae5089fb1e3a03e0f7fd151d to your computer and use it in GitHub Desktop.
Save DragonI/989d0dd4ae5089fb1e3a03e0f7fd151d to your computer and use it in GitHub Desktop.
ES6: Convert From/To Binary/Decimal/Hexadecimal in JavaScript
/**
* Convert From/To Binary/Decimal/Hexadecimal in JavaScript
* https://gist.github.com/faisalman
*
* Copyright 2012-2015, Faisalman <fyzlman@gmail.com>
* 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'
*/
@DragonI
Copy link
Author

DragonI commented Jun 21, 2016

Here's an example on WebpackBin. Check the console for the results

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment