一烛秋风 2023-09-03 02:32 采纳率: 50%
浏览 19
已结题

python的struct.unpack函数在Java中如何替代

我测试过ByteBuffer方法,即使参数一致,但是结果并不一致,求解决方法

python:

import struct


def account_id_to_steam_id(account_id: str) -> str:
    first_bytes = int(account_id).to_bytes(4, byteorder="big")

    print(first_bytes)
    last_bytes = 0x1100001.to_bytes(4, byteorder="big")
    print(first_bytes + last_bytes)
    print(struct.unpack(">Q", last_bytes + first_bytes))
    return str(struct.unpack(">Q", last_bytes + first_bytes)[0])


print(account_id_to_steam_id(account_id="1421145735"))

结果: 76561199381411463

java:

    public static byte[] intToByte4(int i) {
        byte[] targets = new byte[4];
        targets[3] = (byte) (i & 0xFF);
        targets[2] = (byte) (i >> 8 & 0xFF);
        targets[1] = (byte) (i >> 16 & 0xFF);
        targets[0] = (byte) (i >> 24 & 0xFF);
        return targets;
    }

main:
    var b1 = NumberUtil.intToByte4(1421145735);
    var b2 = NumberUtil.intToByte4(17825793);
    byte[] result = Arrays.copyOf(b1, b1.length + b2.length);
    System.arraycopy(b2, 0, result, b1.length, b2.length);
    var buffer = ByteBuffer.wrap(result ) //
                               .order(java.nio.ByteOrder.LITTLE_ENDIAN)
    System.out.println(buffer.getLong());

结果: 72075192800031828

  • 写回答

2条回答 默认 最新

  • threenewbee 2023-09-03 09:02
    关注

    Java的字节序可能不同,你把高低字节颠倒一下看看

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 9月11日
  • 已采纳回答 9月3日
  • 创建了问题 9月3日

悬赏问题

  • ¥100 有偿,谁有移远的EC200S固件和最新的Qflsh工具。
  • ¥15 找一个QT页面+目标识别(行人检测)的开源项目
  • ¥15 有没有整苹果智能分拣线上图像数据
  • ¥20 有没有人会这个东西的
  • ¥15 cfx考虑调整“enforce system memory limit”参数的设置
  • ¥30 航迹分离,航迹增强,误差分析
  • ¥15 Chrome Manifest扩展引用Ajax-hook库拦截请求失败
  • ¥15 用Ros中的Topic通讯方式控制小乌龟的速度,走矩形;编写订阅器代码
  • ¥15 LLM accuracy检测
  • ¥15 pycharm添加远程解释器报错