慕仙森
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 );}将有符号字节打包到int中时,需要屏蔽掉每个字节,因为由于算术提升规则(在JLS,转换和促销中描述),它被符号扩展为32位(而不是零扩展)。Joshua Bloch和Neal Gafter在Java Puzzlers(“每个字节中的大喜悦”)中描述了一个有趣的谜题。将字节值与int值进行比较时,将字节符号扩展为int,然后将此值与另一个int进行比较byte[] bytes = (…)if (bytes[0] == 0xFF) {
// dead code, bytes[0] is in the range [-128,127] and thus never equal to 255}请注意,所有数字类型都使用Java签名,但char是16位无符号整数类型。