3 回答

TA貢獻(xiàn)1777條經(jīng)驗(yàn) 獲得超3個(gè)贊
使用java.nio命名空間中找到的類,特別是ByteBuffer。它可以為您完成所有工作。
byte[] arr = { 0x00, 0x01 };
ByteBuffer wrapped = ByteBuffer.wrap(arr); // big-endian by default
short num = wrapped.getShort(); // 1
ByteBuffer dbuf = ByteBuffer.allocate(2);
dbuf.putShort(num);
byte[] bytes = dbuf.array(); // { 0, 1 }

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超8個(gè)贊
byte[] toByteArray(int value) { return ByteBuffer.allocate(4).putInt(value).array();}byte[] toByteArray(int value) { return new byte[] { (byte)(value >> 24), (byte)(value >> 16), (byte)(value >> 8), (byte)value };}int fromByteArray(byte[] bytes) { return ByteBuffer.wrap(bytes).getInt();}// packing an array of 4 bytes to an int, big endian, minimal parentheses// operator precedence: <<, &, | // when operators of equal precedence (here bitwise OR) appear in the same expression, they are evaluated from left to rightint fromByteArray(byte[] bytes) { return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);}// packing an array of 4 bytes to an int, big endian, clean codeint fromByteArray(byte[] bytes) { return ((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8 ) | ((bytes[3] & 0xFF) << 0 );}
將有符號字節(jié)打包到int中時(shí),需要屏蔽掉每個(gè)字節(jié),因?yàn)橛捎谒阈g(shù)提升規(guī)則(在JLS,轉(zhuǎn)換和促銷中描述),它被符號擴(kuò)展為32位(而不是零擴(kuò)展)。
Joshua Bloch和Neal Gafter在Java Puzzlers(“每個(gè)字節(jié)中的大喜悅”)中描述了一個(gè)有趣的謎題。將字節(jié)值與int值進(jìn)行比較時(shí),將字節(jié)符號擴(kuò)展為int,然后將此值與另一個(gè)int進(jìn)行比較
byte[] bytes = (…)if (bytes[0] == 0xFF) { // dead code, bytes[0] is in the range [-128,127] and thus never equal to 255}
請注意,所有數(shù)字類型都使用Java簽名,但char是16位無符號整數(shù)類型。

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
您還可以將BigInteger用于可變長度字節(jié)。您可以將其轉(zhuǎn)換為long,int或short,以滿足您的需求。
new BigInteger(bytes).intValue();
或表示極性:
new BigInteger(1, bytes).intValue();
要獲取字節(jié)只是:
new BigInteger(bytes).toByteArray()
添加回答
舉報(bào)