Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Hexadecimal

Tags:

python

hex

How to convert decimal to hex in the following format (at least two digits, zero-padded, without an 0x prefix)?

Input: 255 Output:ff

Input: 2 Output: 02

I tried hex(int)[2:] but it seems that it displays the first example but not the second one.

like image 972
VikkyB Avatar asked Feb 03 '13 22:02

VikkyB


People also ask

How do you represent hexadecimal in Python?

When denoting hexadecimal numbers in Python, prefix the numbers with '0x'. Also, use the hex() function to convert values to hexadecimal format for display purposes.

What does hex () in Python do?

The hex() function converts the specified number into a hexadecimal value. The returned string always starts with the prefix 0x .

Does Python support hexadecimal?

Python hex() function is used to convert an integer to a lowercase hexadecimal string prefixed with “0x”. We can also pass an object to hex() function, in that case the object must have __index__() function defined that returns integer. The input integer argument can be in any base such as binary, octal etc.


1 Answers

Use the format() function with a '02x' format.

>>> format(255, '02x') 'ff' >>> format(2, '02x') '02' 

The 02 part tells format() to use at least 2 digits and to use zeros to pad it to length, x means lower-case hexadecimal.

The Format Specification Mini Language also gives you X for uppercase hex output, and you can prefix the field width with # to include a 0x or 0X prefix (depending on wether you used x or X as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:

>>> format(255, '02X') 'FF' >>> format(255, '#04x') '0xff' >>> format(255, '#04X') '0XFF' 
like image 181
Martijn Pieters Avatar answered Sep 28 '22 10:09

Martijn Pieters