首页 > 解决方案 > 将一个无符号的 32 位整数转换为长度为 4 字节的字节数组,在 java 中反之亦然

问题描述

一个无符号的 32 位整数,最小值为 0,最大值为 2 的 32 平方减去 1。我想将其转换为长度为 4 字节的字节数组,反之亦然。当我运行主要方法打击时,一切都是-1?我很困惑。如何从字节数组中获取最大值并将最大值转换为字节数组?还有其他数字?

public static void main(String[] args) {
    long l = (long) Math.pow(2, 32);
    l--;
    byte[] bs = toBytes(l);
    for(byte b:bs){
        System.out.println(b);
    }
    System.out.println("------");
    byte[] arr = { (byte) 0xff, (byte) 0xff,(byte) 0xff,(byte) 0xff };
    System.out.println(fromByteArray(arr));

}

static byte[] toBytes(long i)
{
  byte[] result = new byte[4];

  result[0] = (byte) (i >> 24);
  result[1] = (byte) (i >> 16);
  result[2] = (byte) (i >> 8);
  result[3] = (byte) (i /*>> 0*/);

  return result;
}

 static long fromByteArray(byte[] bytes) {
     return (bytes[0]& 0xFF) << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
}

标签: javanumbers

解决方案


您确实需要研究二进制补码的工作原理,以了解计算机中的符号数。

但是,为了展示有符号值和无符号值之间的区别,请参见此处:

long maxAsLong = 4294967295L; // Unsigned int max value
System.out.println("maxAsLong = " + maxAsLong);

int max = (int) maxAsLong;
System.out.println("max (unsigned) = " + Integer.toUnsignedString(max) +
                                 " = " + Integer.toUnsignedString(max, 16));
System.out.println("max (signed) = " + Integer.toString(max) +
                               " = " + Integer.toString(max, 16));

byte[] maxBytes = ByteBuffer.allocate(4).putInt(max).array();
System.out.print("maxBytes (unsigned): ");
for (byte b : maxBytes)
    System.out.print(Byte.toUnsignedInt(b) + " ");
System.out.println();
System.out.print("maxBytes (signed): ");
for (byte b : maxBytes)
    System.out.print(b + " ");
System.out.println();

int max2 = ByteBuffer.allocate(4).put(maxBytes).rewind().getInt();
System.out.println("max2 (unsigned) = " + Integer.toUnsignedString(max2) +
                                  " = " + Integer.toUnsignedString(max2, 16));

输出

maxAsLong = 4294967295
max (unsigned) = 4294967295 = ffffffff
max (signed) = -1 = -1
maxBytes (unsigned): 255 255 255 255 
maxBytes (signed): -1 -1 -1 -1 
max2 (unsigned) = 4294967295 = ffffffff

推荐阅读