Faced a problem while processing hex numbers.
When running str (hex ())
from a file, the zeros after 0x...
disappear.
At the entrance:
0x0000000000000000000000000000000000000000000000000000000000000001f01f80f12f7cf16638f7a8074d46fe2f421a73432b1441a01ed3dd883c68acad
0x00000000000000000000000000000000000000000000000000000000000000029a799033fc54073346f870c15c9836f6b2e9eccdb85f09d29a8ddc90dc3a8ef1
0x00000000000000000000000000000000000000000000000000000000000000033e561483073e429ec25c09c99de2a81d5a34a539ad2dbb688af6b6f5f24936a4
On exit:
0x1f01f80f12f7cf16638f7a8074d46fe2f421a73432b1441a01ed3dd883c68acad
0x29a799033fc54073346f870c15c9836f6b2e9eccdb85f09d29a8ddc90dc3a8ef1
0x33e561483073e429ec25c09c99de2a81d5a34a539ad2dbb688af6b6f5f24936a4
Code:
with open("data.txt", "r") as file:
for line in file:
L = int(line, 0)
R = str(hex(L))
print(R)
What needs to be fixed in the code? I need one size of numbers and no loss of zeros.
CodePudding user response:
Use string formatting:
#
means put0x
on the front for hex numbers.0130
means the fields is 130 characters long, the leading zero means pad with zeros.x
means hexadecimal (lowercase a-f).
line = '0x0000000000000000000000000000000000000000000000000000000000000001f01f80f12f7cf16638f7a8074d46fe2f421a73432b1441a01ed3dd883c68acad'
print(line) # as read from file
integer = int(line, 0)
formatted = f'{integer:#0130x}'
print(formatted)
print(formatted == line) # check that original and re-formatted are the same
Output:
0x0000000000000000000000000000000000000000000000000000000000000001f01f80f12f7cf16638f7a8074d46fe2f421a73432b1441a01ed3dd883c68acad
0x0000000000000000000000000000000000000000000000000000000000000001f01f80f12f7cf16638f7a8074d46fe2f421a73432b1441a01ed3dd883c68acad
True