mongodb - JavaScript - Convert 24 digit hexadecimal number to decimal, add 1 and then convert back? -
for objectid in mongodb, work 24 digit hexadecimal number. because need keep track of second collection, need add 1 hexadecimal number.
in case, here's value
var value = "55a98f19b27585d81922ba0b"
what i'm looking is
var newvalue = "55a98f19b25785d81922ba0c"
i tried create function this
function hexplusone(hex) { var num = (("0x" + hex) / 1) + 1; return num.tostring(16); }
this works smaller hex numbers
hexplusone("eeefab") => "eeefac"
but fails miserably hash
hexplusone(value) => "55a98f19b275840000000000"
is there better way solve this?
this version return string long input string, overflow ignored in case input "ffffffff".
function hexincrement(str) { var hex = str.match(/[0-9a-f]/gi); var digit = hex.length; var carry = 1; while (digit-- && carry) { var dec = parseint(hex[digit], 16) + carry; carry = math.floor(dec / 16); dec %= 16; hex[digit] = dec.tostring(16); } return(hex.join("")); } document.write(hexincrement("55a98f19b27585d81922ba0b") + "<br>"); document.write(hexincrement("ffffffffffffffffffffffff"));
this version may return string 1 character longer input string, because input "ffffffff" carries on become "100000000".
function hexincrement(str) { var hex = str.match(/[0-9a-f]/gi); var digit = hex.length; var carry = 1; while (digit-- && carry) { var dec = parseint(hex[digit], 16) + carry; carry = math.floor(dec / 16); dec %= 16; hex[digit] = dec.tostring(16); } if (carry) hex.unshift("1"); return(hex.join("")); } document.write(hexincrement("55a98f19b27585d81922ba0b") + "<br>"); document.write(hexincrement("ffffffffffffffffffffffff"));
i curious te see whether user2864740's suggestion of working 12-digit chunks offer advantage. surprise, though code looks more complicated, it's around twice fast. first version runs 500,000 times per second too, it's not you're going notice in real world.
function hexincrement(str) { var result = ""; var carry = 1; while (str.length && carry) { var hex = str.slice(-12); if (/^f*$/i.test(hex)) { result = hex.replace(/f/gi, "0") + result; carry = 1; } else { result = ("00000000000" + (parseint(hex, 16) + carry).tostring(16)).slice(-hex.length) + result; carry = 0; } str = str.slice(0,-12); } return(str.tolowercase() + (carry ? "1" : "") + result); } document.write(hexincrement("55a98f19b27585d81922ba0b") + "<br>"); document.write(hexincrement("000000000000ffffffffffff") + "<br>"); document.write(hexincrement("0123456789abcdef000000000000ffffffffffff"));
Comments
Post a Comment