给定字符串中的整数值,我想将其转换为 2 字节有符号整数。
BigInteger
可以完成这项工作,但我不知道如何授予 2 个字节...
public void handleThisStringValue(String x, String y){
BigInteger bi_x = new BigInteger(x, 10);
BigInteger bi_y = new BigInteger(y, 10);
byte[] byteX = bi_x.toByteArray();
byte[] byteY = bi_y.toByteArray();
}
我注意到 BigInteger.toByteArray()
处理适合我的负值。
然后我需要读取这些值(负值和正值),或者将 byte[2]
转换为 signed int
。有什么建议吗?
最佳答案
嗯,你的问题仍然缺乏某些信息。
首先,Java 整数是 32 位长,因此它们不适合 2 字节数组,您需要一个 4 字节数组,否则您实际上正在处理短数据类型,即 16 位长。
此外,不确定您是否需要处理任何类型的字节顺序(小端、大端)。
无论如何,假设您使用的整数仅适合 16 位和大端字节顺序,您可以执行以下操作来创建字节数组:
public static byte[] toByteArray(String number){
ByteBuffer buffer = ByteBuffer.allocate(4);
buffer.putInt(Integer.parseInt(number));
return Arrays.copyOfRange(buffer.array(), 2, 4); //asumming big endian
}
并按如下方式将其转换回来:
public static int toInteger(byte[] payload){
byte[] data = new byte[4];
System.arraycopy(payload, 0, data, 2, 2);
return ByteBuffer.wrap(data).getInt();
}
您还可以使用ByteBuffer.order
方法更改ByteBuffer的字节顺序。
我的使用方法如下:
byte[] payload = toByteArray("255");
int number = toInteger(payload);
System.out.println(number);
输出为255
关于java - 如何在 Davik VM 上将字符串整数有符号值转换为 2 字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10352304/