Javascript: Decimal to Hex Problem

Hello all,

i would like to convert Decimal to Hex.

the problem i met is:

wenn i tried to convert decimal 987654321 to Hex, i get the value 7267464261. What i really wanted are 3AD168B1.

following are codes.

anyone knows where is the problem?

thanks,
wantime
<html>
<body>


<p id="demo"></p>

<script type="text/javascript">
function DecToHex(d) {return d.toString(8)}
window.onload=function() {
    var dx = DecToHex(987654321);
    document.getElementById("demo").innerHTML= dx;
}

</script>

</body>
</html>

Open in new window

wantimeAsked:
Who is Participating?
 
ProculopsisCommented:

//you are getting Octal, change the base to 16

function DecToHex(d) {return d.toString(16)}
0
 
khan_webguruCommented:
Please use like this

yourNum = yourNum.toString(16);
and reverse the process with:
yourNum = parseInt(yourNum, 16);

Open in new window


reference: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript

Hex to Decimal and Decimal to Hex

 
function d2h(d) {return d.toString(16);}
function h2d(h) {return parseInt(h,16);}

Open in new window


reference: http://javascript.about.com/library/blh2d.htm


In your case just copy past below code and replace your old one it will work fine:

 
<html>
<body>


<p id="demo"></p>

<script type="text/javascript">
function DecToHex(d) {return d.toString(16);}
window.onload=function() {
    var dx = DecToHex(987654321);
    document.getElementById("demo").innerHTML= dx;
}

</script>

</body>
</html>

Open in new window


Thanks,

Asif Ahmed Khan
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.