Skip to content

Instantly share code, notes, and snippets.

@asmattic
Created October 11, 2020 01:49
Show Gist options
  • Save asmattic/5f020f492f0a3cdcbec3c30c469dcd16 to your computer and use it in GitHub Desktop.
Save asmattic/5f020f492f0a3cdcbec3c30c469dcd16 to your computer and use it in GitHub Desktop.
JS Bin // source https://jsbin.com/sezewos
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="[add your bin description]">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script id="jsbin-javascript">
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('');
}
/**
*Alternate version 1
*/
function intToHex(integer) {
let number = (integer).toString(16);
if( (number.length % 2) > 0 ) number = `0${number}`
return number
}
/**
* A function for converting hex <-> dec w/o loss of precision.
*
* The problem is that parseInt("0x12345...") isn't precise enough to convert
* 64-bit integers correctly.
*
* Internally, this uses arrays to encode decimal digits starting with the least
* significant:
* 8 = [8]
* 16 = [6, 1]
* 1024 = [4, 2, 0, 1]
*/
// Adds two arrays for the given base (10 or 16), returning the result.
// This turns out to be the only "primitive" operation we need.
function add(x, y, base) {
let z = [];
let n = Math.max(x.length, y.length);
let carry = 0;
let i = 0;
while (i < n || carry) {
let xi = i < x.length ? x[i] : 0;
let yi = i < y.length ? y[i] : 0;
let zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
}
// Returns a*x, where x is an array of decimal digits and a is an ordinary
// JavaScript number. base is the number base of the array x.
function multiplyByNumber(num, x, base) {
if (num < 0) return null;
if (num === 0) return [];
let result = [];
let power = x;
while (true) {
if (num & 1) {
result = add(result, power, base);
}
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
}
function parseToDigitsArray(str, base) {
let digits = str.split('');
let ary = [];
for (let i = digits.length - 1; i >= 0; i--) {
let n = parseInt(digits[i], base);
if (isNaN(n)) return null;
ary.push(n);
}
return ary;
}
function convertBase(str, fromBase, toBase) {
let digits = parseToDigitsArray(str, fromBase);
if (digits === null) return null;
var outArray = [];
var power = [1];
for (let i = 0; i < digits.length; i++) {
// invariant: at this point, fromBase^i = power
if (digits[i]) {
outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);
}
power = multiplyByNumber(fromBase, power, toBase);
}
let out = '';
for (let i = outArray.length - 1; i >= 0; i--) {
out += outArray[i].toString(toBase);
}
return out;
}
function decToHex(decStr) {
let hex = convertBase(decStr, 10, 16);
return hex ? `0x${hex}` : null;
}
function hexToDec(hexStr) {
if (hexStr.substring(0, 2) === '0x') hexStr = hexStr.substring(2);
hexStr = hexStr.toLowerCase();
return convertBase(hexStr, 16, 10);
}
// Call the function
let number = 16777215; // ffffff
console.log(`Hex conversion number: ${number} => hex: ${toHex(number)} => intToHex: ${intToHex(number)} => decToHex: ${decToHex(number.toString())}`);
</script>
<script id="jsbin-source-javascript" type="text/javascript">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('');
}
/**
*Alternate version 1
*/
function intToHex(integer) {
let number = (integer).toString(16);
if( (number.length % 2) > 0 ) number = `0${number}`
return number
}
/**
* A function for converting hex <-> dec w/o loss of precision.
*
* The problem is that parseInt("0x12345...") isn't precise enough to convert
* 64-bit integers correctly.
*
* Internally, this uses arrays to encode decimal digits starting with the least
* significant:
* 8 = [8]
* 16 = [6, 1]
* 1024 = [4, 2, 0, 1]
*/
// Adds two arrays for the given base (10 or 16), returning the result.
// This turns out to be the only "primitive" operation we need.
function add(x, y, base) {
let z = [];
let n = Math.max(x.length, y.length);
let carry = 0;
let i = 0;
while (i < n || carry) {
let xi = i < x.length ? x[i] : 0;
let yi = i < y.length ? y[i] : 0;
let zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
}
// Returns a*x, where x is an array of decimal digits and a is an ordinary
// JavaScript number. base is the number base of the array x.
function multiplyByNumber(num, x, base) {
if (num < 0) return null;
if (num === 0) return [];
let result = [];
let power = x;
while (true) {
if (num & 1) {
result = add(result, power, base);
}
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
}
function parseToDigitsArray(str, base) {
let digits = str.split('');
let ary = [];
for (let i = digits.length - 1; i >= 0; i--) {
let n = parseInt(digits[i], base);
if (isNaN(n)) return null;
ary.push(n);
}
return ary;
}
function convertBase(str, fromBase, toBase) {
let digits = parseToDigitsArray(str, fromBase);
if (digits === null) return null;
var outArray = [];
var power = [1];
for (let i = 0; i < digits.length; i++) {
// invariant: at this point, fromBase^i = power
if (digits[i]) {
outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);
}
power = multiplyByNumber(fromBase, power, toBase);
}
let out = '';
for (let i = outArray.length - 1; i >= 0; i--) {
out += outArray[i].toString(toBase);
}
return out;
}
function decToHex(decStr) {
let hex = convertBase(decStr, 10, 16);
return hex ? `0x${hex}` : null;
}
function hexToDec(hexStr) {
if (hexStr.substring(0, 2) === '0x') hexStr = hexStr.substring(2);
hexStr = hexStr.toLowerCase();
return convertBase(hexStr, 16, 10);
}
// Call the function
let number = 16777215; // ffffff
console.log(`Hex conversion number: ${number} => hex: ${toHex(number)} => intToHex: ${intToHex(number)} => decToHex: ${decToHex(number.toString())}`);
</script></body>
</html>
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('');
}
/**
*Alternate version 1
*/
function intToHex(integer) {
let number = (integer).toString(16);
if( (number.length % 2) > 0 ) number = `0${number}`
return number
}
/**
* A function for converting hex <-> dec w/o loss of precision.
*
* The problem is that parseInt("0x12345...") isn't precise enough to convert
* 64-bit integers correctly.
*
* Internally, this uses arrays to encode decimal digits starting with the least
* significant:
* 8 = [8]
* 16 = [6, 1]
* 1024 = [4, 2, 0, 1]
*/
// Adds two arrays for the given base (10 or 16), returning the result.
// This turns out to be the only "primitive" operation we need.
function add(x, y, base) {
let z = [];
let n = Math.max(x.length, y.length);
let carry = 0;
let i = 0;
while (i < n || carry) {
let xi = i < x.length ? x[i] : 0;
let yi = i < y.length ? y[i] : 0;
let zi = carry + xi + yi;
z.push(zi % base);
carry = Math.floor(zi / base);
i++;
}
return z;
}
// Returns a*x, where x is an array of decimal digits and a is an ordinary
// JavaScript number. base is the number base of the array x.
function multiplyByNumber(num, x, base) {
if (num < 0) return null;
if (num === 0) return [];
let result = [];
let power = x;
while (true) {
if (num & 1) {
result = add(result, power, base);
}
num = num >> 1;
if (num === 0) break;
power = add(power, power, base);
}
return result;
}
function parseToDigitsArray(str, base) {
let digits = str.split('');
let ary = [];
for (let i = digits.length - 1; i >= 0; i--) {
let n = parseInt(digits[i], base);
if (isNaN(n)) return null;
ary.push(n);
}
return ary;
}
function convertBase(str, fromBase, toBase) {
let digits = parseToDigitsArray(str, fromBase);
if (digits === null) return null;
var outArray = [];
var power = [1];
for (let i = 0; i < digits.length; i++) {
// invariant: at this point, fromBase^i = power
if (digits[i]) {
outArray = add(outArray, multiplyByNumber(digits[i], power, toBase), toBase);
}
power = multiplyByNumber(fromBase, power, toBase);
}
let out = '';
for (let i = outArray.length - 1; i >= 0; i--) {
out += outArray[i].toString(toBase);
}
return out;
}
function decToHex(decStr) {
let hex = convertBase(decStr, 10, 16);
return hex ? `0x${hex}` : null;
}
function hexToDec(hexStr) {
if (hexStr.substring(0, 2) === '0x') hexStr = hexStr.substring(2);
hexStr = hexStr.toLowerCase();
return convertBase(hexStr, 16, 10);
}
// Call the function
let number = 16777215; // ffffff
console.log(`Hex conversion number: ${number} => hex: ${toHex(number)} => intToHex: ${intToHex(number)} => decToHex: ${decToHex(number.toString())}`);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment