【发布时间】:2014-01-27 20:05:02
【问题描述】:
下面是一个将 unsigned 原始类型编码为字节数组并将编码字节数组作为十进制字符串返回的类。我从概念上理解 encodeIntBigEndian 和 byteArrayToDecimalString 的工作原理。但是,我希望您能清楚说明:
- 为什么/如何将
val移动((size - i - 1) * Byte.SIZE)会产生一个无符号Java 字节值。- 另外,为什么应用
0xff的字节掩码会将字节转换为十进制字符串值。
public class BruteForceCoding {
private static byte byteVal = 101; // one hundred and one
private static short shortVal = 10001; // ten thousand and one
private static int intVal = 100000001; // one hundred million and one
private static long longVal = 1000000000001L;// one trillion and one
private final static int BSIZE = Byte.SIZE / Byte.SIZE;
private final static int SSIZE = Short.SIZE / Byte.SIZE;
private final static int ISIZE = Integer.SIZE / Byte.SIZE;
private final static int LSIZE = Long.SIZE / Byte.SIZE;
private final static int BYTEMASK = 0xFF; // 8 bits
public static String byteArrayToDecimalString(byte[] bArray) {
StringBuilder rtn = new StringBuilder();
for (byte b : bArray) {
rtn.append(b & BYTEMASK).append(" ");
}
return rtn.toString();
}
public static int encodeIntBigEndian(byte[] dst, long val, int offset, int size) {
for (int i = 0; i < size; i++) {
dst[offset++] = (byte) (val >> ((size - i - 1) * Byte.SIZE));
}
return offset;
}
public static void main(String[] args) {
byte[] message = new byte[BSIZE + SSIZE + ISIZE + LSIZE];
// Encode the fields in the target byte array
int offset = encodeIntBigEndian(message, byteVal, 0, BSIZE);
offset = encodeIntBigEndian(message, shortVal, offset, SSIZE);
offset = encodeIntBigEndian(message, intVal, offset, ISIZE);
encodeIntBigEndian(message, longVal, offset, LSIZE);
System.out.println("Encoded message: " + byteArrayToDecimalString(message));
}
}
【问题讨论】:
标签: java bit-manipulation