2008-10-22

How to convert Decimal in Hex and Hex in Decimal numbers in JavaScript

Trying to convert decimal numbers in hexadecimal numbers and vice versa, I wanted to use the "modulo 16" (to convert decimal to hex numbers) resp. "modulo 10" (to convert hex to decimal numbers) operations but fortunately, before writing the corresponding functions, I have read the corresponding JavaScript reference and found two functions that saved me some useless effort:

var base = 16
var decimal = 255
var hexadecimal = 'f0b4'
document.writeln('Dec notation: ' + decimal + ' - Hex notation: ' + decimal.toString(base) + '<br/>')
document.writeln('Hex notation: ' + hexadecimal + ' - Dec notation: ' + parseInt(hexadecimal, base) + '<br/>')