ZebraSocks
ZebraSocks

Reputation: 85

Convert decimal to four hex digits

Is there a way to convert decimal numbers to four hex digits? For example:

Decimal: 17    =>   Hex: 0x0011 
Decimal: 291   =>   Hex: 0x0123
Decimal: 4951  =>   Hex: 0x1357

Basically, I want to preserve the leading zeroes.

So far I have:

my $HEX_NUM = sprintf("%x", $DEC_NUM);

Is there a way to get the leading zeros without hardcoding them?

Upvotes: 0

Views: 865

Answers (1)

ysth
ysth

Reputation: 98388

Use a 0 flag and a width in your printf specifier:

sprintf('%04x', $DEC_NUM);

Though from your example, you may also want the '#' flag (but you'd have to increase the width to 6 to accommodate the 0x).

Upvotes: 4

Related Questions