Java字节数组和python字节数组

Java字节数组和python字节数组

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))
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

飞得更高肥尾沙鼠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值