1、区别
Java 字节(Byte) 取值范围: [-128,127]
Python3 字节(bytes) 取值范围: [0,256)
2、相互转换
def pb2jb(byte_arr):
"""
python字节码转java字节码
:param byte_arr:
:return:
"""
return [int(i) - 256 if int(i) > 127 else int(i) for i in byte_arr]
def jb2pb(byte_arr):
"""
java 字节码转python字节码
:return:
"""
return [i + 256 if i < 0 else i for i in byte_arr]
def jb2jb(byte_arr):
"""
[-255,256) 映射 到 [-128 ~ 127]
@param byte_arr:
@return: byte_arr
"""
new_list = []
for i in byte_arr:
if i < -128:
new_list.append(i + 256)
elif i > 127:
new_list.append(i - 256)
else:
new_list.append(i)
return new_list
def hex2jb(hex_str):
"""
十六进制数据转java字节码
eg:
hex_str = "5f 3c f2 81 c8 0f 88 89 c7 b1 99 77 58 c5 4c 04"
:return:
"""
return [int(i, 16) - 256 if int(i, 16) > 127 else int(i, 16) for i in hex_str.split(" ")]
def hex2pb(hex_str):
"""
十六进制数据转python字节码
eg:
hex_str = "5f 3c f2 81 c8 0f 88 89 c7 b1 99 77 58 c5 4c 04"
:return:
"""
return [int(i, 16) for i in hex_str.split(" ")]
def pb2str(byte_arr, encoding="utf-8"):
"""
python字节码转str
:return:
"""
return bytes(byte_arr).decode(encoding)
def jb2str(byte_arr, encoding="utf-8"):
"""
java字节码转str
:return:
"""
return bytes(jb2pb(byte_arr)).decode(encoding)
def hex2str(hex_str, encoding="utf-8"):
"""
hex转str
:param hex_str: "2c 22 70 61 79 63 68 65 63 6b 6d 6f 64 65 22 3a"
:param encoding:
:return:
"""
return bytes(hex2pb(hex_str)).decode(encoding)
使用
byte_list = [97, 105, 100, 61, 50, 52, 54, 51, 56, 55, 53, 55, 49, 38, 97, 117, 116, 111, 95, 112, 108, 97, 121, 61, 48,
38, 99, 105, 100, 61, 50, 56, 57, 48, 48, 56, 52, 52, 49, 38, 100, 105, 100, 61, 75, 82, 69, 104, 69, 83,
77, 85, 74, 104, 56, 116, 70, 67, 69, 86, 97, 82, 86, 112, 69, 50, 116, 97, 80, 81, 107, 55, 87, 67, 104,
67, 74, 103, 38, 101, 112, 105, 100, 61, 48, 38, 102, 116, 105, 109, 101, 61, 49, 54, 50, 55, 49, 48, 48,
57, 51, 55, 38, 108, 118, 61, 48, 38, 109, 105, 100, 61, 48, 38, 112, 97, 114, 116, 61, 49, 38, 115, 105,
100, 61, 48, 38, 115, 116, 105, 109, 101, 61, 49, 54, 50, 55, 49, 48, 52, 51, 55, 50, 38, 115, 117, 98, 95,
116, 121, 112, 101, 61, 48, 38, 116, 121, 112, 101, 61, 51]
print(jb2str(byte_list))