Converting number to hexadecimal [closed]

2020-05-08 02:08发布

As an exercise I am converting numbers to hexadecimal values. Is there a more professional way of doing it?

def hexayacheviren(reqem):
    if reqem==10: 
        return "A"
    elif reqem==11: 
        return "B"
    elif reqem==12: 
        return "C"
    elif reqem==13: 
        return "D"
    elif reqem==14: 
        return "E"
    elif reqem==15: 
        return "F"
    else: 
        return reqem

def hexadecimal(n):
    cavab=[ ]
    i=0
    while (n>0):
        netice=n%16
        cavab.append(hexayacheviren(netice))
        i=i+1
        n=n//16
    string=''.join(str(e) for e in cavab)
    cvbstrng = string[::-1]
    print (cvbstrng)

hexadecimal(3200)

标签: python
3条回答
在下西门庆
2楼-- · 2020-05-08 02:27

Here's my solution using some of Python's more interesting features, like yield, generator comprehension, ternary operator, string indexing, and various bit twiddling miscellanea:

#!/usr/bin/env python

def nibbles(n):
    m = max(4, (n.bit_length()+3) & -4)
    while m > 0:
        m -= 4
        yield (n >> m) & 0x0F

def _hexadecimal(n):
    return "".join("0123456789ABCDEF"[nib] for nib in nibbles(n))

def hexadecimal(n):
    return "-"+_hexadecimal(-n) if n < 0 else _hexadecimal(n)

if __name__ == "__main__":
    import sys
    u = [hexadecimal(i) for i in range(0x10010)]
    v = [hex(i)[2:].upper() for i in range(0x10010)]

    if u == v:
        print("tested ok")
        sys.exit(0)
    else:
        print("test failed!")
        sys.exit(1)
查看更多
够拽才男人
3楼-- · 2020-05-08 02:28

use the builtin function: hex. Python comes batteries included

>>> hex
<built-in function hex>
>>> hex(9)
'0x9'
>>> hex(21)
'0x15'
>>> hex(10101010101010101010101010101010101)
'0x1f204abeac202ce18095d40a57eb5L'
查看更多
劳资没心,怎么记你
4楼-- · 2020-05-08 02:40

You could simply your first function using a dict and possibly throw in a bit of error handling, eg:

def hexayacheviren(reqem):
    if not 0 <= reqem < 16:
        raise ValueError('Out of range')
    return {10: 'A', 11: 'B', 12: 'C', 13: 'D', 14: 'E', 15: 'F'}.get(reqem, str(reqem))

If the value is one of 10, 11, 12... then it returns the corresponding letter, otherwise, it returns the original number as a string. This will lead to you being able to simplify your second functions as its inputs always take an int, and its outputs will always be a string.

查看更多
登录 后发表回答