Home » JavaScript

JavaScript | Convert decimal to hexadecimal and vice versa

JavaScript | Convert decimal to hexadecimal and hexadecimal to decimal: Here, we are going to learn by example how to convert decimal value to the hexadecimal value and vice versa in JavaScript?
Submitted by IncludeHelp, on February 01, 2019

Sometimes we need to convert an integer value which is in decimal format to the hexadecimal string in JavaScript or need a decimal value from a given hexadecimal string.

Read more: How to assign decimal, octal and hexadecimal values to the variables in JavaScript?

In such cases, we can convert a decimal value to the hexadecimal string by using the number.toString(16) and hexadecimal string to the decimal by using hex_string.parseInt(16).

In both cases, 16 is the base to the number system that says that target or source value format is hexadecimal.

Example:

<html>
<head>
<title>JavaScipt Example</title>
</head>

<body>
	<script>		
		var a = 10;
		var b = 12345;
		
		document.write("a = " + a.toString(16) + "<br>");
		document.write("b = " + b.toString(16) + "<br>");
		
		//conver hexadecimal string to the int again
		var hex = "0A"; //hex of 10
		var dec = parseInt(hex,16);
		document.write("dec = " + dec + "<br>");
	</script>
</body>
</html>

Output

a = a
b = 3039
dec = 10




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.