您的位置:首页 > 编程语言 > Python开发

Python刷题笔记(3)- 16进制和ascii码互转

2015-11-18 17:19 721 查看
今天看了下等级标示,原来kyu上面还有dan的等级,升级路漫漫,今天是5kyu题目

题目:

Write a module Converter that can take ASCII text and convert it tohexadecimal. The class should also be able to take hexadecimal andconvert it to ASCII text.

Example

Converter.to_hex("Look mom, no hands")
=> "4c6f6f6b206d6f6d2c206e6f2068616e6473"

Converter.to_ascii("4c6f6f6b206d6f6d2c206e6f2068616e6473")
=> "Look mom, no hands"

中文简介:

就是写个ASCII码和16进制的转换器,可以互相转换。

想法:

1、字符串转16进制,直接使用ord()函数然后逐个转换为16进制,再将16进制数转化成字符串形式加入到列表,再把列表合成字符串返回

2、16进制转换字符串,间隔为2历遍字符串,然后将16进制字符串转换成10进制数字,用char()函数转换为ASCII码加入列表,然后把列表合成字符串返回。

3、int(str,16)可以实现字符串转换成16进制,str()实现转换字符串,hex()函数转换为16进制,但是返回的是0x00形式

实现:

class Converter():
@staticmethod
def to_ascii(h):
list_s = []
for i in range(0,len(h),2):
list_s.append(chr(int(h[i:i+2].upper(),16)))
return ''.join(list_s)
@staticmethod
def to_hex(s):
list_h = []
for c in s:
list_h.append(str(hex(ord(c)))[-2:]) #取hex转换16进制的后两位
return ''.join(list_h)

比较总结:

提交后看到别人的方法实在是简单。。直接使用系统函数encode("hex")和decode("hex")就解决了。。感觉有点作弊啊。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: