You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Python bytearray字节超出0-255范围的报错问题

问题解答

错误根源

单个字节的存储范围为0~255,因此bytearray要求每个元素必须在该区间内,不存在可直接存储大于255数值的单字节。大于255的整数需要按照通信协议约定的规则,拆分为多个字节序列化后再传输。
你当前对接的Minecraft游戏通信协议中,版本号字段采用*VarInt(可变长度整数)*编码,340编码后为两个字节,不能直接作为单个元素写入bytearray。

解决方案

首先实现Minecraft协议要求的VarInt编码函数:

def encode_varint(value: int) -> bytes:
    buffer = b""
    while True:
        current_byte = value & 0x7F
        value >>= 7
        if value != 0:
            buffer += bytes([current_byte | 0x80])
        else:
            buffer += bytes([current_byte])
            break
    return buffer

修改原有的握手包构造逻辑,将版本号编码后再写入bytearray:

import socket

def encode_varint(value: int) -> bytes:
    buffer = b""
    while True:
        current_byte = value & 0x7F
        value >>= 7
        if value != 0:
            buffer += bytes([current_byte | 0x80])
        else:
            buffer += bytes([current_byte])
            break
    return buffer

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 10000))
s.connect(("127.0.0.1", 25565))

handshake = bytearray([6,0])
handshake.extend(encode_varint(340)) # 编码后的游戏版本号
handshake.extend([0,0,69,2])
s.send(handshake)

补充说明

如果后续遇到其他大于255的数值字段,需要按照Minecraft协议要求选择对应编码方式(如VarLong、固定长度大/小端整数等)序列化后再拼接,不要直接将原始整数作为单元素写入bytearray。

内容的提问来源于stack exchange,提问作者talaing

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 21:15:09