将八进制和十六进制数转换为基数 10
我试图理解 javascript 八进制和十六进制计算。我知道我可以使用 parseInt(string, radix) 来获取整数值。
例如,当我尝试这样做时,为什么值会不同?
var octal = parseInt('026', 8);
var octal1 = parseInt('030', 8);
alert(octal); //22
alert(octal1); //24
var hex = parseInt('0xf5', 16);
var hex1 = parseInt('0xf8', 16);
alert(hex); //245
alert(hex1); //248
但是,如果我尝试将其保存在数组中,为什么答案会不同且不正确?
var x = new Array(026, 5, 0xf5, "abc");
var y = new Array(030, 3, 0xf8, "def");
alert('026 is ' + parseInt(x[0],8)); //18
alert('0xf5 is ' + parseInt(x[2],16)); //581
alert('030 is ' + parseInt(y[0],8)); //20
alert('0xf8 is ' + parseInt(y[2],16)); //584
I am trying to understand javascript octal and hexadecimal computations. I know I can use parseInt(string, radix)
to get the Integer value.
For example, when I try this why are the values different?
var octal = parseInt('026', 8);
var octal1 = parseInt('030', 8);
alert(octal); //22
alert(octal1); //24
var hex = parseInt('0xf5', 16);
var hex1 = parseInt('0xf8', 16);
alert(hex); //245
alert(hex1); //248
But if I try to save it in an array why are the answers different and incorrect?
var x = new Array(026, 5, 0xf5, "abc");
var y = new Array(030, 3, 0xf8, "def");
alert('026 is ' + parseInt(x[0],8)); //18
alert('0xf5 is ' + parseInt(x[2],16)); //581
alert('030 is ' + parseInt(y[0],8)); //20
alert('0xf8 is ' + parseInt(y[2],16)); //584
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
parseInt
在解析参数之前将其转换为字符串:所以:
数组中的内容大部分已经是数字,因此无需解析它们。如果将它们更改为字符串,您将得到预期的结果:
parseInt
converts the argument to string before parsing it:So:
What you have in your arrays are mostly already numbers so there is no need to parse them. You will get expected results if you change them to strings:
我编写了一个函数,可以将数字从一个基数转换为另一个基数,其中起始基数和新基数被指定为参数。
http://jsfiddle.net/jarble/p9ZLa/
I've written a function that can convert a number from one base to another, where the starting base and the new base are specified as parameters.
http://jsfiddle.net/jarble/p9ZLa/
在字符串外部看到的
0xf5
是整数245
;它不是需要解析的字符串:同样,字符串外部的
026
是整数22
:您所做的是传递已经转换为 base10 的值整数转换为
parseInt()
,然后将它们转换为字符串并将 base10 解释为 base16,再次执行基数转换。0xf5
seen outside a string is the integer245
; it is not a string that needs to be parsed:Similarly,
026
outside a string is the integer22
:What you're doing is passing already-converted-to-base10 integers to
parseInt()
, which then converts them to strings and interprets the base10 as base16, performing the base conversion a second time.