Hex to Hex String

huangapple go评论62阅读模式
英文:

Hex to Hex String

问题

I am converting hex to hex strings then came across 2 ways to do it using the toString() method:

  • toString('hex')
  • toString(16)

I see a lot of resources online also use toString('hex') but when I tried to use it, it gives out an error message: RangeError: toString() radix argument must be between 2 and 36.
The toString(16) works perfectly.

But just for curiosity, what is the story behind this? Is the toString('hex') deprecated in some way? Or is there any specific use-case when that is used instead of toString(16)?

Example:

let num = 0x7

console.log('Convert using toString('hex'): ' + num.toString('hex')) // throws an error
console.log('Convert using toString(16): ' + num.toString(16))
英文:

I am converting hex to hex strings then came across 2 ways to do it using the toString() method:

  • toString('hex')
  • toString(16)

I see a lot of resources online also use toString('hex') but when I tried to use it, it gives out an error message: RangeError: toString() radix argument must be between 2 and 36.
The toString(16) works perfect.

But just for curiousity, what is the story behind this? Is the toString('hex') deprecated of some sort? Or is there any specific use-case when that is used instead of toString(16)

Example:

let num = 0x7

console.log('Convert using toSting(hex): ' + num.toString('hex')) // throws an error
console.log('Convert using toSting(16): ' + num.toString(16))

答案1

得分: 1

.toString(16) 是将Numbers转换为十六进制字符串的方法,.toString('hex') 是将NodeJS的Buffers转换为十六进制字符串的方法。

对于Numbers,radix 是一个可选参数,它应该是一个从2到36的整数,其默认值为10。

toString([radix])

对于Buffers,encoding 是一个可选参数(起始和结束也是可选的),它可以是许多之一(还可以参考这个答案),如"ascii","utf8",以及在这种情况下,"hex",其默认值为"utf8"。

toString([encoding[, start[, end]]])

如果你混合使用这些,Number 将抛出一个RangeErrortoString() radix argument must be between 2 and 36),而Buffer 将抛出一个TypeErrorUnknown encoding: 16)。

英文:

.toString(16) is how you convert Numbers to a hex string, .toString('hex') is how you convert NodeJS's Buffers to a hex string.

For Numbers, radix is an optional parameter, which should be an integer from 2 to 36, with a default value of 10.

toString([radix])

For Buffers, encoding is an optional parameter (with start and end also optional), which can be many values (also see this answer) such as "ascii", "utf8", and, in this case, "hex", with the default value of "utf8".

toString([encoding[, start[, end]]])

If you mix-match these, Number will throw a RangeError (toString() radix argument must be between 2 and 36) and Buffer will throw a TypeError (Unknown encoding: 16)

huangapple
  • 本文由 发表于 2023年2月10日 16:04:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75408367.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定