I try to convert a number between 0 and 255 to hexadecimal format. If I use sprintf("%X", 1)
I get 1
, but I need the output always to have width 2 (with leading 0s) instead of one. How can this be done?
Use "%02x" . The two means you always want the output to be (at least) two characters wide. The zero means if padding is necessary, to use zeros instead of spaces.
To print integer number in Hexadecimal format, "%x" or "%X" is used as format specifier in printf() statement. "%x" prints the value in Hexadecimal format with alphabets in lowercase (a-f). "%X" prints the value in Hexadecimal format with alphabets in uppercase (A-F).
// the %% format specifiers. The %x %X format specifiers: The %x or %X format specifier is used to represent the integer Hexadecimal value. %x displays the hexadecimal values with lowercase alphabets whereas the %X specifier displays the hexadecimal values with uppercase alphabets.
Try: printf("%04x",a); 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified. x - Specifier for hexadecimal integer.
Use %02X
:
sprintf("%02X",1) # -> "01" sprintf("%02X",10) # -> "0A" sprintf("%02X",16) # -> "10" sprintf("%02X",255) # -> "FF"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With