Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert decimal to hex missing padded 0

Tags:

javascript

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.

like image 282
user1754493 Avatar asked Jun 20 '13 02:06

user1754493


People also ask

How to convert decimal 0 to hexadecimal?

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.

How to convert decimal 15 to Hex?

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.

What is the hex equivalent of a decimal number?

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.

How to write hexadecimal numbers with leading zeros?

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.


2 Answers

Using String.padStart:

(d).toString(16).padStart(2, '0')
like image 158
Jonatan Avatar answered Sep 30 '22 05:09

Jonatan


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.

like image 35
icktoofay Avatar answered Sep 30 '22 07:09

icktoofay