简体   繁体   English

在Java中将无符号的32位整数转换为字节数组,长度为4字节,反之亦然

[英]convent a unsigned 32 bit integer to byte array which length is 4 byte and vice versa in java

a unsigned 32 bit integer,min is 0,max is The 32 square of 2 minus 1.I want to convent it to byte array which length is 4 byte and vice versa . 一个无符号的32位整数,min为0,max为2的32平方减1。我想将其限制为长度为4个字节的字节数组,反之亦然。 When I run the main method blow,everything is -1?I am so puzzled. 当我运行主方法打击时,一切都是-1吗?我很困惑。 How to get the max from byte array and convent the max to byte array?And other number? 如何从字节数组中获取最大值并将其转换为字节数组?

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);
}

You really need to study how two's complement works, to understand signed numbers in computers. 您确实需要研究二进制补码的工作原理,以了解计算机中的带符号数字。

But, to showcase the difference between signed and unsigned values, see here: 但是,要展示有符号和无符号值之间的差异,请参见此处:

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));

Output 输出量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM