Skip to content

Instantly share code, notes, and snippets.

@faisalman
Last active January 11, 2023 14:43
Show Gist options
  • Save faisalman/4213592 to your computer and use it in GitHub Desktop.
Save faisalman/4213592 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-2015, Faisalman <fyzlman@gmail.com>
* Licensed under The MIT License
* http://www.opensource.org/licenses/mit-license
*/
(function(){
var ConvertBase = function (num) {
return {
from : function (baseFrom) {
return {
to : function (baseTo) {
return parseInt(num, baseFrom).toString(baseTo);
}
};
}
};
};
// binary to decimal
ConvertBase.bin2dec = function (num) {
return ConvertBase(num).from(2).to(10);
};
// binary to hexadecimal
ConvertBase.bin2hex = function (num) {
return ConvertBase(num).from(2).to(16);
};
// decimal to binary
ConvertBase.dec2bin = function (num) {
return ConvertBase(num).from(10).to(2);
};
// decimal to hexadecimal
ConvertBase.dec2hex = function (num) {
return ConvertBase(num).from(10).to(16);
};
// hexadecimal to binary
ConvertBase.hex2bin = function (num) {
return ConvertBase(num).from(16).to(2);
};
// hexadecimal to decimal
ConvertBase.hex2dec = function (num) {
return ConvertBase(num).from(16).to(10);
};
this.ConvertBase = ConvertBase;
})(this);
/*
* Usage example:
* ConvertBase.bin2dec('111'); // '7'
* ConvertBase.dec2hex('42'); // '2a'
* ConvertBase.hex2bin('f8'); // '11111000'
* ConvertBase.dec2bin('22'); // '10110'
*/
@Aravin
Copy link

Aravin commented Aug 28, 2020

To convert large binary to hex use this code

https://gist.github.com/Aravin/011f17528f90be6bb4f5a4cb253647d6

@jadsongmatos
Copy link

based on the suggestion of @SeanCannon I made this conversion from utf8 to binary, I just tested node

const convert = {
  utfBin: (s) => parseInt(Buffer.from(s, "utf-8").toString("hex"), 16).toString(2),
  binUtf: (s) => Buffer.from(parseInt(s, 2).toString(16), "hex").toString("utf-8"),
};

const bin = convert.utfBin("1808z");
console.log("utfBin: ", bin);

console.log("binUtf: ", convert.binUtf(bin));

@EBugYT
Copy link

EBugYT commented Dec 18, 2022

thanks very much. i like this project so.

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