Skip to content

Instantly share code, notes, and snippets.

@szkrd
Created March 11, 2016 21:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save szkrd/c2f1f7117afd3701a8e2 to your computer and use it in GitHub Desktop.
Save szkrd/c2f1f7117afd3701a8e2 to your computer and use it in GitHub Desktop.
'use strict'
var int = require('int')
function hexToDec (s) {
const map = '0123456789abcdef'
let power = 0
let res = 0
for (let i = s.length - 1; i >= 0; i--) {
const currentDigit = s.substr(i, 1)
res = int(res).add(
int(map.indexOf(currentDigit)).mul(int(16).pow(power))
)
power++
}
return(res.toString())
}
function decToRadix(num, radix) {
const map = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~'
radix = radix || (map.length - 1)
let hex = ''
let chrPos
num = int(num)
while (!num.eq(0)) {
chrPos = int(num).mod(radix).toString() * 1
hex = map.charAt(chrPos) + hex
num = int(num.sub(chrPos).toString()).div(radix)
}
return hex
}
console.log(hexToDec('12345678ff24') === '20015998369572')
console.log(hexToDec('f5345ff324ffffffffff') === '1157945932905430848110591')
console.log(hexToDec('507f191e810c19729de860ea') === '24912452986661892666266509546')
const id = '507f191e810c19729de860ea'
console.log(id)
console.log(decToRadix(hexToDec(id))) // "p9P2GoMRqPBhfMQq"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment