leodutra
12/3/2015 - 8:33 PM

JavaScript decimal, hexadecimal, octal, binary manipulation.

JavaScript decimal, hexadecimal, octal, binary manipulation.

function baseTobase(n, base1, base2) {
  return parseInt(n, base1).toString(base2);
}

function decToHex(n) {
  // more about >>> for negatives
  // here: http://stackoverflow.com/a/17106974/1260526
  // here: https://en.wikipedia.org/wiki/Two%27s_complement
  // and here: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#Bitwise_shift_operators
  return (n >>> 0).toString(16); 
}

function hexToDec(n) {
  return parseInt(n, 16);
}

function hexToBin(n) {
  return parseInt(n, 10).toString(2);
}

function decToBin(n) {
  return n.toString(2);
}

function binToDec(n) {
  return parseInt(n, 2);
}

function binToHex(n) {
  return parseInt(n, 2).toString(16);
}