Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

padding zero for hexadecimal number in php

Tags:

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
like image 671
Santosh Pillai Avatar asked Sep 02 '25 02:09

Santosh Pillai


1 Answers

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

like image 55
Elven Spellmaker Avatar answered Sep 04 '25 16:09

Elven Spellmaker