27

I have a hexadecimal number in javascript. For display purposes, I would like to format the string as:

ffffffff-ffff-ffff
00000000-0000-01ff

(8 digits)-(4 digits)-(4 digits) with padded zeros on the front

I've been trying to write my own loop to format an arbitrary hexadecimal number into this format, but this seems like something that should be available in JavaScript already.

Is there a built-in way to format a hexadecimal number in JavaScript?

1
  • There is unfortunately no way to format such hexadecimal numbers in JavaScript. But check out this link, maybe it helps.
    – Neq
    Mar 28, 2012 at 14:05

7 Answers 7

59

I would do a two-step process:

1) convert number to 16 digit hex with leading zeros:

var i = 12345; // your number
var h = ("000000000000000" + i.toString(16)).substr(-16);

2) add dashes

var result = h.substr(0, 8)+'-'+h.substr(8,4)+'-'+h.substr(12,4);
0
15

Further to knabar's answer:

If your number is really a full 64 bits long you should be aware that javascript has only doubles, which top out at around 53 bits of precision. E.g.

var i = 0x89abcdef01234567; // a 64-bit constant
var h = ("000000000000000" + i.toString(16)).substr(-16); // "89abcdef01234800"

So you probably want to split this into two 32-bit numbers, and format them 8 digits at a time. Then the second caveat strikes: javascript performs bitwise ops on signed 32-bit integers, and this formatting code can't handle negative numbers.

var i = 0xffd2 << 16; // actually negative
var h = ("0000000" + i.toString(16)).substr(-8); // "0-2e0000"

Since it's fairly likely that numbers you want formatted in hexadecimal are the result of bitwise manipulations, the code can be tweaked to print in two's complement instead:

var i = 0xffd2 << 16; // actually negative
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "ffd20000"

This produces the hex representation of the bottom 32 bits of the integral part of arbitrary positive and negative numbers. This is probably what you want (it's approximately printf("%08x")). Some more corner cases:

var i = 1.5; // non-integers are rounded
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "00000001"

var i = -1.5; // rounding is towards zero
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "ffffffff"

var i = NaN; // not actually a number
var h = ("0000000" + ((i|0)+4294967296).toString(16)).substr(-8); // "00000000"
1
  • While (i|0)+4294967296 will adequately force the number to be in range and unsigned, i >>> 0 achieves this purpose as well, and it's a lot clearer too. Oct 2, 2020 at 17:15
14

ES6 Version

function toPaddedHexString(num, len) {
    str = num.toString(16);
    return "0".repeat(len - str.length) + str;
}

var hexStr = toPaddedHexString(12345, 16);
1
  • 5
    This is simplified further by padStart in EMCAScript 2017. num.toString(16).padStart(len, "0")
    – Chris_F
    Dec 4, 2018 at 17:36
7

There are two methods for String called padStart and padEnd

const num = 15;
console.log(num.toString(16).padStart(2, "0")); // "0f"
const num = 15;
console.log(num.toString(16).padEnd(2, "0")); // "f0"

Additional information on the link: padStart, padEnd

2

The shortest version as conclusion

For ID like 00000000-0000-01ff

This is rewritten and shorted version from Adam Leggett answer.

function createID_8_4_4(s)
{
	return(1e16+s).slice(-16).replace(/^.{8}|.{4}(?!$)/g,'$&-')
	/*
	    OR the version for easy understanding:
	    return(1e16+s).slice(-16).match(/..../g).join('-').replace('-','')
	    replace on the end replaces only first '-'
	*/
}

console.log(createID_8_4_4('01ff')); //00000000-0000-01ff

For ID like 0000-0000-0000-01ff

function createID_4_4_4_4(s)
{
	return(1e16+s).slice(-16).match(/..../g).join('-')
}

console.log(createID_4_4_4_4('01ff')); //0000-0000-0000-01ff

1

i don't think there is anything related to that in pure javascript, but frameworks provide this method, in ExtJS 3 it is implemented this way

    /**
     * Pads the left side of a string with a specified character.  This is especially useful
     * for normalizing number and date strings.  Example usage:
     * <pre><code>
var s = String.leftPad('123', 5, '0');
// s now contains the string: '00123'
     * </code></pre>
     * @param {String} string The original string
     * @param {Number} size The total length of the output string
     * @param {String} char (optional) The character with which to pad the original string (defaults to empty string " ")
     * @return {String} The padded string
     * @static
     */
    leftPad : function (val, size, ch) {
        var result = String(val);
        if(!ch) {
            ch = " ";
        }
        while (result.length < size) {
            result = ch + result;
        }
        return result;
    }
1
  • This is just a padding function, what about the hex formatting and the dashes?
    – maerics
    Mar 28, 2012 at 14:06
1

I assume the number is already in the form of a string due to the limitations described in hexwab's answer. If it isn't, start the process by getting it into a hex string of arbitrary length (called str) using whatever mechanism is appropriate for your situation. Then:

function format(str) {
  return (1e15+str).slice(-16).match(/^.{8}|.{4}/g).join('-');
}

console.log(format('723e9f4911'))

2
  • Very nice and short solution! (+) I wrote a little bit shorted version from your answer. See my answer.
    – Bharata
    Apr 21, 2020 at 15:59
  • @Bharata I love golf! Let's do this. Amended my answer. Apr 21, 2020 at 18:55

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.