bytes,strings,decimal and hex in python3

python中字节,字符和整数之间的转换

decimal and hex

1
2
3
4

hex(16) #==>0x10
#hex to decimal
int('0x10',16) #==>16

strings to int

1
2
3
4
5
6
#string to decimal
int('10') #==>10
#string to hex
int('10',16) #==>16
#hexic string to hex
int('0x10',16) #==>16

bytes to int

1
2
3
4
#to int (one byte)
struct.unpack('B',bytes(b'x01')) #==>(1,) a tuple
#to long int (four bytes)
struct.unpack('<L',bytes(b'x01x00x00x00')) #==>(1,)

int to bytes

1
2
3
4
#to one byte
struct.pack('B',1) #==>b'x01'
#to two bytes
struct.pack('HH',1,2) #==>b'x01x00x02x00'

strings to bytes

1
2
3
4
#to syllabified code
'12abc'.encode('ascii') ==> b'12abc'
#to hexadecimal bytes
bytes().fromhex('010210') ==> b'x01x02x10'

bytes to strings

1
2
3
4
5
6
7
8
9
#decode to strings
bytes(b'x31x32x61x62').decode('ascii') ==> 12ab
#to hexadecimal bytes
str(bytes(b'x01x0212'))[2:-1] ==> x01x0212

hex to byte
---
```python
hex(16).encode('adcii') ==> b'x10'

用格式化

`
print(“%X”%255) #输出大写十六进制的FF
各种数据类型之间的转换见博客
python常用的十进制,十六进制,字符串,字节串之间的转换
unpack函数的格式见博客Python使用struct处理二进制(pack和unpack用法)