ARTICLE AD BOX
I am trying to convert from byte[4] to int, and int to byte[4]. But Why java need the operation of "(bytes[0] & 0xFF)" thing? Because, you know, in bit level, when you are doing "&0xFF", the bit 0 is still 0, 1 is still 1. Why?
public class ByteUtil { public static int unsignedByteToInt(byte[] bytes) { if(bytes == null || bytes.length != 4) { return -1; } return ((int)(bytes[0] & 0xFF)<< 24) | ((int)(bytes[1] & 0xFF) << 16) | ((int)(bytes[2] & 0xFF) << 8) | ((int)(bytes[3] & 0xFF)); } public static byte[] intToUnsignedByte(int value) { byte[] bytes = new byte[] { (byte) ((value >> 24) & 0xFF), (byte) ((value >> 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); } }