I have this function here:
function d2h(d) { return (+d).toString(16); }
So say I put d2h(15);
.
This will return f
. I need it to return 0f
.
To convert decimal number 0 to hexadecimal, follow these steps: Divide 0 by 16 keeping notice of the quotient and the remainder. Continue dividing the quotient by 16 until you get a quotient of zero. Then just write out the remainders in the reverse order to get hexadecimal equivalent of decimal number 0.
For example, the decimal number 15 will be F in hex. Step 2: If the given decimal number is 16 or greater, divide the number by 16. Step 3: Write down the remainder.
Step 1: If the given decimal number is less than 16, the hex equivalent is the same. Remembering that the letters A, B, C, D, E and F are used for the values 10, 11, 12, 13, 14 and 15, convert accordingly.
Suppose you want to have leading zeros for hexadecimal number, for example you want 7 digit where your hexadecimal number should be written on, you can do like that : None of the answers are dealing well with negative numbers... ' {:0 {}X}'.format (val & ( (1 << nbits)-1), int ( (nbits+3)/4)) will set the width correct.
Using String.padStart
:
(d).toString(16).padStart(2, '0')
The most obvious way would be to check if it's only one character, and if so, add a zero before it:
function d2h(d) {
var s = (+d).toString(16);
if(s.length < 2) {
s = '0' + s;
}
return s;
}
A less obvious way would be this:
function d2h(d) {
return (d / 256 + 1 / 512).toString(16).substring(2, 4);
}
But that's too tricky; I'd definitely stick with the first solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With