将表示为字符串的十进制数转换为十六进制格式,仍然表示为字符串

Convert a decimal number represented as a string to its hex format still representing it as a string

本文关键字:字符串 表示 格式 十进制数 转换 十六进制      更新时间:2023-09-26

我正试图使用bigInteger.js库在160位整数中进行运算,但我想保留这些整数的十六进制格式表示,这样我就可以传输它们并将它们用作ID。

var git_sha1 = require('git-sha1');
var bigInt = require("big-integer");
var uuid = git_sha1((~~(Math.random() * 1e9)).toString(36) + Date.now());
console.log('in hex 't', uuid); // See the uuid I have
console.log('in dec 't', bigInt(uuid, 16).toString()); // convert it to bigInt and then represent it as a string
console.log('to hex 't', bigInt(uuid, 16).toString(16)); // try to convert it back to hex

这是我的输出:

in hex   4044654fce69424a651af2825b37124c25094658
in dec   366900685503779409298642816707647664013657589336
to hex   366900685503779409298642816707647664013657589336

我需要to hexin hex相同。有什么建议吗?非常感谢。

这是通过https://github.com/peterolson/BigInteger.js/pull/18

我不知道你是否如此依恋big-integer,但如果你不是,bigint会做你想要的事情。

编辑:如果你想保持大整数,这应该做的技巧:

function toHexString(bigInt) {
  var output = '';
  var divmod;
  while(bigInt.notEquals(0)) {
    divmod = bigInt.divmod(16);
    bigInt = divmod.quotient;
    if (divmod.remainder >= 10)
      output = String.fromCharCode(87+divmod.remainder) + output;
    else
      output = divmod.remainder + output;
  }
  return output;
}