Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/rust/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 字节数组到*Signed*Int_Java_Bytearray_Signed - Fatal编程技术网

Java 字节数组到*Signed*Int

Java 字节数组到*Signed*Int,java,bytearray,signed,Java,Bytearray,Signed,我正在尝试将-101转换为字节数组,然后将字节数组转换回-101。我下面的方法适用于正值,但不适用于负值。你能指出我做错了什么吗?方法返回65435,而不是-101。谢谢 /** * Converts a <code>byte</code> array to a 32-bit <code>int</code>. * * @param array The <code>byte</code> array to conve

我正在尝试将
-101
转换为字节数组,然后将字节数组转换回
-101
。我下面的方法适用于正值,但不适用于负值。你能指出我做错了什么吗?方法返回
65435
,而不是
-101
。谢谢

/**
 * Converts a <code>byte</code> array to a 32-bit <code>int</code>.
 * 
 * @param array The <code>byte</code> array to convert.
 * @return The 32-bit <code>int</code> value.
 */
public static int byteArrayToInt(byte[] array) {
  ValidationUtils.checkNull(array);
  int value = 0;

  for (int i = 0; i < array.length; i++) {
    int shift = (array.length - 1 - i) * 8;
    value = value | (array[i] & 0xFF) << shift;
  }

  return value;
}

/**
 * Converts a 32-bit <code>int</code> to a <code>byte</code> array.
 * 
 * @param value The 32-bit <code>int</code> to convert.
 * @return The <code>byte</code> array.
 */
public static byte[] intToByteArray(int value, int size) {
  byte[] bytes = new byte[size];
  for (int index = 0; index < bytes.length; index++) {
    bytes[index] = (byte) (value >>> (8 * (size - index - 1)));
  }
  return bytes;
}

/**
 * Tests the utility methods in this class.
 * 
 * @param args None.
 */
public static void main(String... args) {
  System.out.println(byteArrayToInt(intToByteArray(32, 2)) == 32); // true
  System.out.println(byteArrayToInt(intToByteArray(64, 4)) == 64); // true
  System.out.println(byteArrayToInt(intToByteArray(-101, 2)) == -101); // false
  System.out.println(byteArrayToInt(intToByteArray(-101, 4)) == -101); // true
}

你需要签名并延长你的电话号码。若你们还并没有,你们应该读一读有符号二进制数的表示法

作为32位整数的数字
-101
是十六进制的
0xffff9b
。将其转换为2字节的字节数组。只剩下
0xFF9B
。现在,当您将其转换回时,您将其转换为32位整数,结果是十进制的
0x0000FF9B
,或
65435

您应该检查字节数组中的最高阶位,并在此基础上对扩展进行签名。一种简单的方法是,如果设置了最高阶位,则从
value=-1开始,如果未设置,则默认为
value=0

编辑:检查最高阶位的简单方法是检查高阶字节是否为负