Santosh Pillai
Santosh Pillai

Reputation: 1391

padding zero for hexadecimal number in php

Not sure what I am doing wrong here. When I pad zeros in front of a hexadecimal number it seems to change the number.

$number=1741;
strtoupper(dechex($number))
output is 6CD

sprintf('%03x', strtoupper(dechex($number))
output is 006

Upvotes: 4

Views: 4696

Answers (2)

Elven Spellmaker
Elven Spellmaker

Reputation: 400

The accepted answer says to use sprintf twice. I don't see the value in doing this twice, %x accepts the same padding parameters as %d does and so this can be done in one function call.

$number = 141;

$hex = sprintf('%03X', $number); // 08D

See: https://3v4l.org/LQrWK

So to answer the question, just remove the strtoupper(dechex(...)) and the sprintf you have will work.

echo sprintf('%03x', $number); // 06d

echo sprintf('%03X', $number); // 06D

Upvotes: 7

Murad Hasan
Murad Hasan

Reputation: 9583

For padding zero of a number just use sprintf, If you need a hexadecimal number then you need to use something like sprintf with a valid format for showing hexadecimal number.

Example:

Syntax: sprintf(format,arg1,arg2,arg++)

Format:

  • %x - Hexadecimal number (lowercase letters)
  • %X - Hexadecimal number (uppercase letters)

So, use a sprintf to get the hexadeimal number and then use another sprintf to get the zero padding number.

$number = 141;

$hex = sprintf("%X", $number); //8D
$s = sprintf('%03d', $hex); // 08D

Upvotes: 3

Related Questions