byte/ byte 数组转换成16进制字符串 (需要Netty)
ByteBufUtil.hexDump(new byte[]{0x11, 0x11, 0x11, 0x11})
ByteBufUtil.hexDump(new byte[]{(byte)0xff})
byte 转换成无符号Long / Int表示
byte i = (byte) 0xff;
Long i1 = Byte.toUnsignedLong(i)
Long i2 = Byte.toUnsignedInt(i)
长度为2 byte 数组转换成无符号Int
Unpooled.wrappedBuffer(new byte[]{0x11, 0x11}).readUnsignedShort();
长度为3 byte 数组转成无符号Int
Unpooled.wrappedBuffer(new byte[]{0x11, 0x11, 0x11}).readUnsignedMedium()
长度为4 byte 数组转成无符号Long
byte[] bytes = {(byte) 0xFF, (byte) 0xFF, (byte) 0xFF, (byte) 0xFF};
long l1 = ByteBuffer.wrap(bytes)
.order(ByteOrder.LITTLE_ENDIAN).getInt() & 0xFFFFFFFFL;
long l2 = Unpooled.wrappedBuffer(bytes).readUnsignedInt();
byte 转换成二级制字符串表示
byte b = 0b01000000;
String replace = String.format("%8s", Integer.toBinaryString(b & 0xFF)).replace(' ', '0');
byte 数组转成二进制字符串表示
@Test
public void testBin() {
byte[] byteArr = new byte[]{(byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff};
String s = toBitString(byteArr);
System.out.println(s);
}
public static String toBitString(final byte[] b) {
final char[] bits = new char[8 * b.length];
for (int i = 0; i < b.length; i++) {
final byte byteval = b[i];
int bytei = i << 3;
int mask = 0x1;
for (int j = 7; j >= 0; j--) {
final int bitval = byteval & mask;
if (bitval == 0) {
bits[bytei + j] = '0';
} else {
bits[bytei + j] = '1';
}
mask <<= 1;
}
}
return String.valueOf(bits);
}