Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

printf

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?

like image 666
Marius Hofert Avatar asked Jun 17 '12 09:06

Marius Hofert


People also ask

How do you print a leading zero in hexadecimal?

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.

How do you print hexadecimal numbers?

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).

What format specifier should be used to print a hex value?

// 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.

How do you show hex numbers?

Try: printf("%04x",a); 0 - Left-pads the number with zeroes (0) instead of spaces, where padding is specified. x - Specifier for hexadecimal integer.


1 Answers

Use %02X:

sprintf("%02X",1)    # ->  "01" sprintf("%02X",10)   # ->  "0A" sprintf("%02X",16)   # ->  "10" sprintf("%02X",255)  # ->  "FF" 
like image 53
Joao Tavora Avatar answered Sep 21 '22 21:09

Joao Tavora