-
-
Save mendes5/12b76390d1ae94e8c8175b6dcf0b45ae to your computer and use it in GitHub Desktop.
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
// 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