下面是一个类,它将无符号基元类型编码为字节数组,并将编码的字节数组返回为十进制字符串。我从概念上理解 encodeIntBigEndian
和 byteArrayToDecimalString
的工作原理。不过,我希望能澄清以下问题:
- Why/how shifting the
val
by((size - i - 1) * Byte.SIZE)
produces an unsigned java byte value.- Also, why does applying a byte mask of
0xff
convert the byte to a decimal string value.
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));
}
}
最佳答案
1)它本身并没有。它的作用是将值向下移动一个字节为单位。但是,当与丢弃高位的 (byte)
转换结合使用时,这相当于从值中提取各个字节的移位和掩码操作。
2)事实并非如此。它屏蔽掉高位,保留值的低八位(一个字节)——与前一种情况中执行的转换为字节的操作相同。但是,默认情况下,将字节呈现为字符串会生成一个包含表示其二进制值(从 0 到 255)的十进制数的字符串,并且在调用 .append() 时会隐式发生这种情况。
关于java - 位摆弄 : Encoding Unsigned Primitives,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21390542/