[英]How to String-Integer signed value to 2 byte array on the Davik VM?
给定一个字符串的整数值,我想将其转换为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位长的short数据类型。
另外,不确定是否需要处理任何字节顺序(小字节序,大字节序)。
无论如何,假设您使用的整数仅适合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
int x = bs[0] | ((int)bs[1] << 8);
if (x >= 0x8000) x -= 0x10000;
// Reverse
bs[0] = (byte)(x & 0xFF);
bs[1] = (byte)((x >> 8) & 0xFF);
您可以反过来:
new BigInteger(byteX);
new BigInteger(byteY);
正是您想要的,然后可以使用.intvalue()
将其作为int
解决方案很简单,基于我在这里找到的帖子(谢谢大家):
请记住,我想要一个2字节的整数...所以它很短!
String val= "-32";
short x = Short.parseShort(val);
byte[] byteX = ByteBuffer.allocate(2).putShort(x).array();
...而且有效!
然后,我正在使用BigInteger读回它!
int x1 = new BigInteger(byteX).intValue();
要么
short x2 = new BigInteger(x).shortValue();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.