[docs] discrepancy in result by hex()

Sunil Bahelia 12358.sunila at gmail.com
Sat Jun 29 10:56:49 EDT 2019


The hex() works fine overall but for numbers less than 16 it doesn't gives
right output
for e.g
>>> hex(15)
'0xf'
where it should have been '0x0f'

I have built a method to do the same:
1)
def int2hex(n):
    val={
                10:"A",
                11:"B",
                12:"C",
                13:"D",
                14:"E",
                15:"F"
                }
    s=""
    if(n<0):
        print("negative number not allowed")
        return
    if(n<16):
        if(n<10):
            return "0x0"+str(n)
        else:
            return "0x"+val.get(n)
    while(n>0):
        z=n%16
        if(z<10):
            s=s+str(z)
        else:
            s=s+val.get(z)
        n=n//16

    return "0x"+s

*OR*
*#using hex function*
def int2hex(n):
    val={
                10:"A",
                11:"B",
                12:"C",
                13:"D",
                14:"E",
                15:"F"
                }
    s=""
    if(n<16):
        if(n<10):
            return "0x0"+str(n)
        else:
            return "0x"+val.get(n)
    else:
        return hex(n)


Regards,
Sunil
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/docs/attachments/20190629/538bdb49/attachment.html>


More information about the docs mailing list