Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

How do you convert numbers between different bases in JavaScript?

I would like to convert numbers between different bases, such as hexadecimal and decimal.

Example: How do you convert hexadecimal 8F to decimal?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The API

To convert to a number from a hex string:

parseInt(string, radix)
  • string: Required. The string to be parsed

  • radix: Optional. A number (from 2 to 36) that represents the numeral system to be used

To convert from a number to a hex string:

NumberObject.toString(radix)
  • radix: Optional. Specifies the base radix you would like the number displayed as.

Example radix values:

  • 2 - The number will show as a binary value
  • 8 - The number will show as an octal value
  • 16 - The number will show as an hexadecimal value

Example Usage

Integer value to hex:

var i = 10;
console.log( i.toString(16) );

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...