mathlete
mathlete

Reputation: 6682

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

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?

Upvotes: 33

Views: 105443

Answers (1)

joao
joao

Reputation: 3566

Use %02X:

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

Upvotes: 73

Related Questions