无符号32位整数,min为0,max为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);
}
答案 0 :(得分:0)
您真的需要研究two's complement的工作原理,以了解计算机中已签名的数字。
但是,要展示有符号值和无符号值之间的区别,请参见此处:
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