Starting with Python 3.6, you can:
>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'
Note the padding includes the 0x. If you don't want that you can do
>>> f"0x{value:0{padding}x}"
'0x00002a'
for older python versions use the .format() string method:
>>> "{0:#0{1}x}".format(42,6)
'0x002a'
Explanation:
{ # Format identifier
0: # first parameter
# # use "0x" prefix
0 # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x # hexadecimal number, using lowercase letters for a-f
} # End of format identifier
If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:
>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
Answer from Tim Pietzcker on Stack OverflowStarting with Python 3.6, you can:
>>> value = 42
>>> padding = 6
>>> f"{value:#0{padding}x}"
'0x002a'
Note the padding includes the 0x. If you don't want that you can do
>>> f"0x{value:0{padding}x}"
'0x00002a'
for older python versions use the .format() string method:
>>> "{0:#0{1}x}".format(42,6)
'0x002a'
Explanation:
{ # Format identifier
0: # first parameter
# # use "0x" prefix
0 # fill with zeroes
{1} # to a length of n characters (including 0x), defined by the second parameter
x # hexadecimal number, using lowercase letters for a-f
} # End of format identifier
If you want the letter hex digits uppercase but the prefix with a lowercase 'x', you'll need a slight workaround:
>>> '0x{0:0{1}X}'.format(42,4)
'0x002A'
If you don't need to handle negative numbers, you can do
"{:02x}".format(7) # '07'
"{:02x}".format(27) # '1b'
Where
:is the start of the formatting specification for the first argument{}to.format()02means "pad the input from the left with0s to length2"xmeans "format as hex with lowercase letters"
You can also do this with f-strings:
f"{7:02x}" # '07'
f"{27:02x}" # '1b'
Perhaps you're looking for the .zfill method on strings. From the docs:
Help on built-in function zfill: zfill(...) S.zfill(width) -> string Pad a numeric string S with zeros on the left, to fill a field of the specified width. The string S is never truncated.
Your code can be written as:
def padhexa(s):
return '0x' + s[2:].zfill(8)
assert '0x00000123' == padhexa('0x123')
assert '0x00ABCD12' == padhexa('0xABCD12')
assert '0x12345678' == padhexa('0x12345678')
I would suggest interpreting the input as a number, then using standard number-formatting routines.
padded = str.format('0x{:08X}', int(mystring, 16))
The string → int → string round trip may seem silly, but it is also beneficial in that it provides validation of the input string.
How can I get the "format" function to leave my leading ZEROs in place?
Python , Printing Hex removes first 0? - Stack Overflow
Python Binary to hex conversion preserving leading zeroes - Stack Overflow
[2021 Day 16] Help on turning hex into binary?
You should not always have leading zeroes, such as if the first character of the input is F.
More on reddit.comin python3 hex(0) will return 0x0. Is there any way to make it return 0x00 ?
This is happening because hex() will not include any leading zeros, for example:
>>> hex(15)[2:]
'f'
To make sure you always get two characters, you can use str.zfill() to add a leading zero when necessary:
>>> hex(15)[2:].zfill(2)
'0f'
Here is what it would look like in your code:
fc = '0x'
for i in b[0x15c:0x15f]:
fc += hex(ord(i))[2:].zfill(2)
>>> map("{:02x}".format, (10, 13, 15))
['0a', '0d', '0f']
The total number of hex digits you want, starting from binary string b, is
hd = (len(b) + 3) // 4
So...:
x = '%.*x' % (hd, int('0b'+b, 0))
should give you what you want (with a '0x' prefix that you can easily slice away of course, just use x[2:]).
Added: the format string '%.*x' means "format as hexadecimal to a length as per supplied parameter, with leading zeros". The "supplied parameter" here is hd, the total number of hex digits we require.
The simple, key concept is to think in terms of total number of digits (binary on input, hex on output) rather than the "number of leading zeros" in each case -- the latter will just fall into place. E.g, if the input binary string has 576 bits, no matter how many of them are "leading zeros", you want the output hex string to have 576 // 4, i.e, 144, hex digits, so that's what hd will be set to -- and that's how many digits you'll get by this formatting (as many of them will be "leading zeros" as needed -- no more, no less).
Did you know there's a hex() builtin? It converts any number (including binary numbers, starting with 0b) to a hex string:
>>> hex(0b000011110111101011000101)
'0xf7ac5'
My code for turning hexadecimal into binary works well, but I can't understand when I should have leading zeroes like the example shows. Here are some examples of what I got.
def hexadecimal_to_binary(hex):
integer = int(hex, 16)
binary = format(integer, "0>42b")
return binary
#example one, need to remove all leading zeroes
print(hexadecimal_to_binary("D2FE28"))
>> 000000000000000000110100101111111000101000
#example two, needs two leading zeroes it doesn't have
print(hexadecimal_to_binary("38006F45291200"))
>> 111000000000000110111101000101001010010001001000000000 I think I have the rest of my code pretty close to correct, I'm just struggling on this part. Could you help me out?
You should not always have leading zeroes, such as if the first character of the input is F.
Currently, your code pads the binary string to have 42 digits if it has less than that - you need to make it based on the actual length of the hex string. One hex digit becomes 4 binary digits.
To answer your question specifically, you should have leading zero(es) if the first character in the input is less than 8, since that means that (according to the hex mapping) its first character is a 0.