十进制转十六进制 ← Python字符串

【知识点】
chr() 函数与 ord() 函数示例:

>>> ord('0')
48
>>> chr(48)
'0'
>>> ord('9')
57
>>> chr(57)
'9'
>>> ord('A')
65
>>> chr(65)
'A'
>>> ord('F')
70
>>> chr(70)
'F'

● 巧妙利用字符串的“连接”功能,实现结果输出。
具体到本例代码中,关键是不能将语句 
hex=chr(t+ord('0'))+hex 写成 hex=hex+chr(t+ord('0'))

【输入样例】
123

【输出样例】
7B

【十进制转十六进制 Python 代码】

def toHex(n):
    hex=""
    while n!=0:
        t=n%16
        if 0<=t<=9:hex=chr(t+ord('0'))+hex
        else:hex=chr(t-10+ord('A'))+hex
        n=n//16

    print(hex)

x=eval(input())
toHex(x)

十进制转二进制 Python 代码

def toBin(n):
    bin=""
    while n!=0:
        t=n%2
        bin=chr(t+ord('0'))+bin
        n=n//2

    print(bin)

x=eval(input())
toBin(x)



【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/134089268
https://blog.csdn.net/hnjzsyjyj/article/details/142204614

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值