Search code examples
pythontexthex

convert numbers in text file to base16 in python


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


Solution

  • 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 an 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