我测试过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
Java的字节序可能不同,你把高低字节颠倒一下看看
【以下回答由 GPT 生成】
在Java中替代Python的struct.unpack函数可以尝试使用java.nio.ByteBuffer来实现相同的功能。下面是具体的解决方案:
import java.nio.ByteBuffer;
public class NumberUtil {
public static void main(String[] args) {
String account_id = "1421145735";
int first_bytes = Integer.parseInt(account_id);
int last_bytes = 0x1100001;
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putInt(last_bytes);
buffer.putInt(first_bytes);
buffer.flip(); // 切换为读模式
long steam_id = buffer.getLong(); // 获取steam id
System.out.println(steam_id);
}
}
这里使用了ByteBuffer的allocate方法创建一个容量为8字节的ByteBuffer对象,并使用putInt方法按照大端字节序依次存入两个整数值。然后通过flip方法切换为读模式,使用getLong方法获取steam id,并输出结果。
希望以上的解决方案能够帮到你。如果有其他问题,请随时提问。