在Java中int和byte[]的相互转换

之前的项目中,在Socket通信的时候需要传int类型的值,不过java中outputsteam貌似不能直接传int类型,只能传byte[],所以在这里记录一下int和byte[]互转的方法。

/** 
* int转byte[] 
*/ 
public static byte[] intToBytes(int i) { 
byte[] bytes = new byte[4]; 
bytes[0] = (byte) (i & 0xff); 
bytes[1] = (byte) ((i >> 8) & 0xff); 
bytes[2] = (byte) ((i >> 16) & 0xff); 
bytes[3] = (byte) ((i >> 24) & 0xff); 
return bytes; 
}

接收的时候再转一下即可

/** 
* byte[]转int 
*/ 
public static int bytesToInt(byte[] bytes) { 
int i; 
i = (int) ((bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) 
| ((bytes[2] & 0xff) << 16) | ((bytes[3] & 0xff) << 24)); 
return i; 
}

以上所述是小编给大家介绍的在Java中int和byte[]的相互转换,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!