Я пытаюсь преобразовать byte[4] в int и int в byte[4]. Но зачем Java нужна операция «(bytes[0] & 0xFF)»? Потому что, вы знаете, на уровне битов, когда вы выполняете «&0xFF», бит 0 по-прежнему равен 0, а бит 1 по-прежнему равен 1. Почему?
public class ByteUtil {
public static int unsignedByteToInt(byte[] bytes) {
if(bytes == null || bytes.length != 4) {
return -1;
}
return ((int)(bytes[0] & 0xFF)> 16) & 0xFF),
(byte) ((value >> 8) & 0xFF),
(byte) (value & 0xFF)
};
return bytes;
}
public static void main(String[] args) {
int value = 0xfffefdfc;
byte[] bytes = intToUnsignedByte(value);
System.out.print("int to bytes: \n\t");
if(bytes != null) {
for(byte b : bytes) {
System.out.format("%02x, ", b);
}
}
System.out.println();
int newValue = unsignedByteToInt(bytes);
System.out.format("New Value Get: %02x", newValue);
}
}
Подробнее здесь: https://stackoverflow.com/questions/798 ... ation-0xff