33

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Marius Hofert
  • 6,546
  • 10
  • 48
  • 102

1 Answers1

70

Use %02X:

sprintf("%02X",1)    # ->  "01"
sprintf("%02X",10)   # ->  "0A"
sprintf("%02X",16)   # ->  "10"
sprintf("%02X",255)  # ->  "FF"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
joao
  • 3,517
  • 1
  • 31
  • 43
  • 1
    With Ruby 2.1+, sprintf("%02x",10) -> "0a". Need to do a sprintf("%02X", 10) -> "0A" (note the capital 'X') – Steve Wilhelm Aug 06 '15 at 00:13
  • Oh right, I'm not sure this question is for ruby or any language I know. But perhaps your comment holds for more languages/versions and an edit is in order... – joao Aug 06 '15 at 00:22