整数转换字节:int.to_bytes()
字符串转换字节:bytes()
class Chart_Conversion:
def int_to_bytes(self,num,byteorder,length,signedflag=True):
'''
返回表示整数的字节数组————格式:int.to_bytes(length, byteorder, *, signed=False)
:param num: 要转换为byte的数字
:param byteorder:参数确定用于表示整数的字节顺序。如果 byteorder 是 "big" ,则最高有效字节位于字节数组的开头。
如果 byteorder 是 "little" ,则最高有效字节位于字节数组的末尾。
要请求主机系统的本机字节顺序,请使用sys.byteorder 作为字节顺序值。
:param length:整数使用length 字节表示。如果整数不能用给定的字节数表示,则会引发 OverflowError
:param signedflag:参数确定是否使用二进制补码来表示整数。如果 signed 是 False 并且给定一个负整数,则会引发 OverflowError。
signed 的默认值为 False
'''
if byteorder=='big':
return num.to_bytes(length,'big',signed=signedflag)
else:
return num.to_bytes(length,'little',signed=signedflag)
def string_to_bytes(self,string):
if (type(string) == str):
n = []
for x in string:
n.append(ord(x))
'''
ord() 函数是 chr() 函数(对于8位的ASCII字符串)或 unichr() 函数(对于Unicode对象)的配对函数,
它以一个字符(长度为1的字符串)作为参数,返回对应的 ASCII 数值,或者 Unicode 数值,如果所给的 Unicode 字符超出了你的 Python
定义范围,则会引发一个 TypeError 的异常。
'''
if len(n) > 0:
return (True, bytes(n))
else:
return (False, [], "为空")
else:
return (False, [], "类型必须为字符串")
c=Chart_Conversion()
c.string_to_bytes('1234567890')
print('第34行:',c.int_to_bytes(13,'big',2,True))
print('第35行:',c.int_to_bytes(13,'little',2,True))
print('第36行:',c.int_to_bytes(-13,'big',2,True))
print('第37行:',c.int_to_bytes(-13,'little',2,True))
print('第69行:',c.string_to_bytes('1234567890'))
print('第70行',len((c.string_to_bytes('1234567890'))[1]))
test='abc'
print('第72行:',bytes(test,encoding='utf8'))
print('第73行:',test.encode())
#输出结果
第34行: b'\x00\r'
第35行: b'\r\x00'
第36行: b'\xff\xf3'
第37行: b'\xf3\xff'
第69行: (True, b'1234567890')
第70行 10
第72行: b'abc'
第73行: b'abc'