gpt4 book ai didi

java - 将 12 个字符转换为长整型

转载 作者:行者123 更新时间:2023-12-02 01:09:02 25 4
gpt4 key购买 nike

交易的授权金额。格式为“n 12”,长度为 6 个字节,例如值 1234567 存储为十六进制 00 00 01 23 45 67

TLV > 9F02 06 000001234567

:如何将000001234567转换为1234567

我尝试了如下但不起作用:

public static long byteArrayToLong(@NonNull byte[] from, int offset, @NonNull EEndian endian) {
try {
byte[] fromFixed = new byte[8];
if(from.length < 8) {
System.arraycopy(from, 0, fromFixed, fromFixed.length-from.length, from.length);
}
else {
System.arraycopy(from, 0, fromFixed, 0, fromFixed.length);
}
if (endian == EEndian.BIG_ENDIAN) {
return ((fromFixed[offset] << 24) & 0xff00000000000000L) | ((fromFixed[offset + 1] << 16) & 0xff000000000000L)
| ((fromFixed[offset + 2] << 8) & 0xff0000000000L) | ((fromFixed[offset + 3]) & 0xff00000000L)
| ((fromFixed[offset + 4] << 24) & 0xff000000) | ((fromFixed[offset + 5] << 16) & 0xff0000)
| ((fromFixed[offset + 6] << 8) & 0xff00) | (fromFixed[offset + 7] & 0xff);
} else {
return ((fromFixed[offset + 7] << 24) & 0xff00000000000000L) | ((fromFixed[offset + 6] << 16) & 0xff000000000000L)
| ((fromFixed[offset + 5] << 8) & 0xff0000000000L) | ((fromFixed[offset + 4]) & 0xff00000000L)
| ((fromFixed[offset + 3] << 24) & 0xff000000) | ((fromFixed[offset + 2] << 16) & 0xff0000)
| ((fromFixed[offset + 1] << 8) & 0xff00) | (fromFixed[offset] & 0xff);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return -1;
}

//调用上面的代码

byte[] amountAuthorisedNumeric = transLogResponse.getAmountAuthorisedNumeric(i); // new byte[] {(byte)00x00, (byte)0x00, (byte)0x01, (byte)0x23, (byte)0x45, (byte)0x67}
Log.i(TAG, "AMOUNT1 is " + byteArrayToHexString(amountAuthorisedNumeric)); // 000001234567

amount = byteArrayToLong(amountAuthorisedNumeric, 0, BIG_ENDIAN); // error in here
Log.i(TAG, "AMOUNT2 is " + amount); // 19088743 (result expected is 1234567, not 19088743)

最佳答案

我建议使用 BigInteger

import java.math.BigInteger;

/**
*
* @author Sedrick
*/
public class Main
{

public static void main(String[] args)
{
String value = "000001234567";
BigInteger bigInteger = new BigInteger(value);
System.out.println(bigInteger.longValue());
}

}

输出:

--- exec-maven-plugin:1.5.0:exec (default-cli) @ JavaTestingGround ---
1234567
------------------------------------------------------------------------
BUILD SUCCESS

另一条路线是使用 Long 来解析值。

/**
*
* @author Sedrick
*/
public class Main
{

public static void main(String[] args)
{
String value = "000001234567";

System.out.println(Long.parseLong(value));
}

}

输出:

1234567
------------------------------------------------------------------------
BUILD SUCCESS

关于java - 将 12 个字符转换为长整型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59631696/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com