I have a Text File With Numbers in Base10 Format
2325552
3213245
And i want to convert the Numbers in This text File Using Python Script To Base16 Format So the New Text file Will Be Like that Using Python Script
237C30
3107BD
Thanks In Advance
CodePudding user response:
We can convert integer number to string hex and transfer string write to the file. Example we can transfer to bytearray
CodePudding user response:
Function to convert decimal to hexadecimal
Just pass the number you want to concert to the hex()
method and you'll get back the value in base16 (hexadecimal).
This is and example :
def decimal_to_hexadecimal(dec):
first_v = str(dec)[0]
decimal = int(dec)
if first_v == '-':
hex_dec = hex(decimal)[3:]
else:
hex_dec = hex(decimal)[2:]
return hex_dec
result = decimal_to_hexadecimal(2325552)
print('result : ', result)
Output
result : 237c30
CodePudding user response:
Use hex() the Built-in Functions to convert an integer number to a lowercase hexadecimal string prefixed with “0x”
>>> hex(2325552)
'0x237c30'
If you want to remove the 0x
prefix you the following code
>>> hex(2325552)[2:]
'237c30'
To avoid the error in case of a negative number
use the function described in this answer