为什么JavaScript中的`btoa`编码适用于20位数字的字符串而不适用于20位数字的int? [英] Why does `btoa` encoding in javascript works for 20 digit string and not 20 digit int?
问题描述
考虑以下btoa
输出
btoa(99999999999999999999)
"MTAwMDAwMDAwMDAwMDAwMDAwMDAw"
btoa(99999999999999999998)
"MTAwMDAwMDAwMDAwMDAwMDAwMDAw"
btoa("99999999999999999998")
"OTk5OTk5OTk5OTk5OTk5OTk5OTg="
btoa("99999999999999999999")
"OTk5OTk5OTk5OTk5OTk5OTk5OTk="
我们看到btoa
无法编码20位int
的唯一哈希,但是能够编码20位string
.为什么会这样?
We see that btoa
is unable to encode unique hash for 20 digit int
but was able to encode 20 digit string
. Why is this?
我最初的猜测是,由于btoa
是基数64
,因此它只能编码小于基数64
的内容,但是为什么它却能够编码20位的数字string
?
My original guess is that since btoa
is base 64
it can only encode something that is less than base 64
, but why is it capable of encoding a 20 digit string
instead?
此外,btoa似乎无法编码小于9223372036854775807
的int
Moreover btoa seems to not able to encode int
less than 9223372036854775807
which is a 2^63
btoa(9223372036854775302)
"OTIyMzM3MjAzNjg1NDc3NjAwMA=="
btoa(9223372036854775303)
"OTIyMzM3MjAzNjg1NDc3NjAwMA=="
推荐答案
由于浮点数不精确.请记住,JavaScript在某些计算过程中只是暂时没有 integers ;所有JavaScript数字都是IEEE-754双精度浮点数. 99999999999999999999
在IEEE-754数字中不是一个安全的整数值,实际上,如果您这样做:
Because of floating point imprecision. Remember, JavaScript doesn't have integers except temporarily during certain calculations; all JavaScript numbers are IEEE-754 double-precision floating point. 99999999999999999999
is not a safe integer value in IEEE-754 numbers, and in fact if you do this:
console.log(99999999999999999999);
...你会看到的
100000000000000000000
最大安全整数(例如,不受浮点不精确度影响的整数)为9007199254740991
.
The max safe integer (e.g., integer that won't be affected by floating point imprecision) is 9007199254740991
.
由于btoa
接受 string (当您将数字传递给数字时,数字只会转换为字符串),因此只需在值周围加上引号即可:
Since btoa
accepts a string (when you pass it a number, the number just gets converted to string), just put quotes around your value:
btoa("99999999999999999999")
=> OTk5OTk5OTk5OTk5OTk5OTk5OTk=
当然,如果该值是数学计算的结果,则不能这样做.您必须更改计算如此大的数字的原因,因为它们超出了数字类型的精确范围.
Of course, if the value is the result of a math calculation, you can't do that. You'll have to change whatever it is that's calculating such large numbers, as they exceed the precise range of the number type.
这篇关于为什么JavaScript中的`btoa`编码适用于20位数字的字符串而不适用于20位数字的int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!