Skip to content

Instantly share code, notes, and snippets.

@mendes5
Forked from faisalman/baseConverter.js
Last active August 29, 2019 17:27
Show Gist options
  • Save mendes5/12b76390d1ae94e8c8175b6dcf0b45ae to your computer and use it in GitHub Desktop.
Save mendes5/12b76390d1ae94e8c8175b6dcf0b45ae to your computer and use it in GitHub Desktop.
Convert From/To Binary/Decimal/Hexadecimal in JavaScript
// This is licensed under the terms of the WTFPL license
const convert = (from, to) => value => parseInt(value, from).toString(to);
// Works with any bases btw
// convert(2, 10)('111') // '7'
// convert(10, 16)('42') // '2a'
// convert(16, 2)('f8') // '11111000'
// convert(10, 2)('22') // '10110'
// You can even cache those
export const bin2dec = convert(2, 10);
export const bin2hex = convert(2, 16);
export const dec2bin = convert(10, 2);
export const dec2hex = convert(10, 16);
export const hex2bin = convert(16, 2);
export const hex2dec = convert(16, 10);
export default convert;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment