java - 将一个无符号的 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);
}
解决方案
您确实需要研究二进制补码的工作原理,以了解计算机中的符号数。
但是,为了展示有符号值和无符号值之间的区别,请参见此处:
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
推荐阅读
- node.js - 新的 package.json `exports` 字段不适用于 TypeScript
- google-apps-script - 如果单元格“y”大于单元格“x”,则自动将单元格“y”复制到单元格“x”
- python - Dash(Python) - 计算后无法在数据表中显示数据框
- ios - Swift如何暂停音频
- javascript - Anychart标签云规模
- c# - 无法从 while 函数返回字符串
- javascript - firebase - Reference.set 失败:第一个参数在属性“users.undefined.profileImageUrl”中包含未定义
- python - 在networkx python中,如何将一组新的节点和边连接到图中的每个节点?
- python - 如何根据以逗号分隔的唯一列值将熊猫数据框列中的文本转换为一个热编码列
- android - 不通过 TextViewCompat.setTextAppearance “即时”更改样式