[英]convent a unsigned 32 bit integer to byte array which length is 4 byte and vice versa in java
一個無符號的32位整數,min為0,max為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);
}
您確實需要研究二進制補碼的工作原理,以了解計算機中的帶符號數字。
但是,要展示有符號和無符號值之間的差異,請參見此處:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.