Skip to content

Instantly share code, notes, and snippets.

@asmattic
Created October 11, 2020 09:50
Show Gist options
  • Save asmattic/2d23c4c6fb22be03c2bddf1d08e911c3 to your computer and use it in GitHub Desktop.
Save asmattic/2d23c4c6fb22be03c2bddf1d08e911c3 to your computer and use it in GitHub Desktop.
function toHex(num) {
const base = 16;
const hexVals = '0123456789abcdef';
let hex = [];
let sign = 1;
if(num === 0) return '0';
if(num < 0) {
sign = -1;
num = -num;
}
while(num) {
let remainder = num % base;
num = (num - remainder) / base;
hex.push(hexVals[remainder]);
}
if(sign === 1) {
return hex.reverse().join('');
} else {
let j = hex.length;
let carryDig = 1;
for(let i = 0; i < j; i++) {
if(hex[i] !== '0' || !carryDig) {
hex[i] = hexVals[base - 1 + carryDig - hexVals.indexOf(hex[i])];
carryDig = 0
}
}
// Check fo carry digit
if(carryDig) hex.push('1');
}
return 'f'.repeat(8 - hex.length) + hex.reverse().join('');
}
/**
* @Matt
*/
function decimalToHex(num) {
// Exit immediately if no calculations or variables are needed
if(num === 0) return '0';
const base = 16;
const hexVals = '0123456789abcdef';
let hexCharArray = [];
const isNumPositive = num < 0 ? false : true;
if(!!isNumPositive) num = Math.abs(num);
while(num) {
const remainder = num % base;
num = (num - remainder) / base;
hexCharArray.push(hexVals[remainder]);
}
if(isNumPositive) return hexCharArray.reverse().join('');
let carryDig = 1;
hexCharArray = hexCharArray.map((hexChar, idx) => {
let returnChar = '';
if(hexChar !== '0' || !carryDig) {
returnChar = hexVals[base - 1 + carryDig - hexVals.indexOf(hexChar)];
carryDig = 0;
return returnChar;
}
});
// Check for carry digit
if(carryDig) hexCharArray.push('1');
return 'f'.repeat(base/2 - hexCharArray.length) + hexCharArray.reverse().join('');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment