How do I print a hexadecimal number with leading 0 to have width 2 using sprintf?

printf, r

Solution

Use `%02X`:

sprintf("%02X",1)    # ->  "01"
sprintf("%02X",10)   # ->  "0A"
sprintf("%02X",16)   # ->  "10"
sprintf("%02X",255)  # ->  "FF"

Problem

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?

Original source

Related problems