python字节转换

Python08

python字节转换,第1张

import struct

struct.pack("i", 200).encode('hex')

struct.pack("f", 3.14).encode('hex')

'hello'.encode('hex')

struct.unpack('i','c8000000'.decode('hex'))[0]

round(struct.unpack('f','c3f54840'.decode('hex'))[0],5)

'68656c6c6f'.decode('hex')

'{%s}' % ','.join([str(int(i,16)) for i in re.findall(r'.{2}','68656c6c6f')])

''.join([hex(int(i))[2:] for i in re.findall(r'\d+','{104,101,108,108,111}')])

Python 2.7.12 (default, Nov 22 2016, 17:23:24)

[GCC 4.4.7 20120313 (Red Hat 4.4.7-17)] on linux2

Type "copyright", "credits" or "license()" for more information.

>>>import struct

>>>struct.pack("f", 3.14).encode('hex')

'c3f54840'

>>>round(struct.unpack('f','c3f54840'.decode('hex'))[0],5)

3.14

>>>struct.pack("i", 200).encode('hex')

'c8000000'

>>>struct.unpack('i','c8000000'.decode('hex'))[0]

200

>>>'68656c6c6f'.decode('hex')

'hello'

>>>'hello'.encode('hex')

'68656c6c6f'

>>>import re

>>>'{%s}' % ','.join([str(int(i,16)) for i in re.findall(r'.{2}','68656c6c6f')])

'{104,101,108,108,111}'

>>>''.join([hex(int(i))[2:] for i in re.findall(r'\d+','{104,101,108,108,111}')])

'68656c6c6f'

1、首先将输入的01字符串利用int函数转化为int形式,然后再用hex()函数将其转换成十六进制。

2、将字符串s编码,返回一个bytes类型sc。对于bytes类型,尝试解包时,你会获得这一字节的整数(0~255)然后通过bin函数将其转换成二进制字符串形式。

3、但是bin方法返回的字符串首先开头是’0b’其次他的第一位必定为1,会吞掉在此之前的0,我们用一个右对齐rjust()在前面填零。最后的join起到一个字符串拼接的作用。