byte[]和int相互转换备份
2016-07-30 00:00
260 查看
import java.nio.ByteOrder; /** */ public class AnyIdUtil { public final static boolean IS_BIG_ENEIAN = (ByteOrder.nativeOrder() == ByteOrder.BIG_ENDIAN); public static byte[] int2bytes(int value) { byte[] bytes = new byte[4]; if (!IS_BIG_ENEIAN) { // 小端 bytes[3] = (byte) ((value >> 24) & 0xFF); bytes[2] = (byte) ((value >> 16) & 0xFF); bytes[1] = (byte) ((value >> 8) & 0xFF); bytes[0] = (byte) (value & 0xFF);//byte[0] 存储 数据高位 } else {//大端 bytes[0] = (byte) ((value >> 24) & 0xFF); //byte[0] 存储数据高位 bytes[1] = (byte) ((value >> 16) & 0xFF); bytes[2] = (byte) ((value >> 8) & 0xFF); bytes[3] = (byte) (value & 0xFF); } return bytes; } public static int bytes2int(byte[] bytes) { int value = 0; if (!IS_BIG_ENEIAN) { value = (int) ((bytes[0] & 0xFF) | ((bytes[1] & 0xFF) << 8) | ((bytes[2] & 0xFF) << 16) | ((bytes[3] & 0xFF) << 24)); } else { value = (int) (((bytes[0] & 0xFF) << 24) | ((bytes[1] & 0xFF) << 16) | ((bytes[2] & 0xFF) << 8) | (bytes[3] & 0xFF)); } return value; } }
这个更好理解:
public static int byte4ToInt(byte[] bytes, int off) {
int b0 = bytes[off] & 0xFF;
int b1 = bytes[off + 1] & 0xFF;
int b2 = bytes[off + 2] & 0xFF;
int b3 = bytes[off + 3] & 0xFF;
return (b0 << 24) | (b1 << 16) | (b2 << 8) | b3;
}
相关文章推荐
- byte[]到short、int、long的相互转换
- int 与 byte[] 的相互转换
- java中byte数组与int类型之间的相互转换(两种方式)
- byte数组和Int之间的相互转换
- byte,int,char,double的相互转换(java)
- int、char、double与byte相互转换的程序
- java中int与byte〔4〕的相互转换
- 整型int和字符数组byte相互转换的源程序
- int、char、double与byte相互转换的程序
- Java中有关byte和String的转换笔记和byte[]到short、int、long的相互转换
- 在Java中int和byte[]的相互转换
- java中int与byte的相互转换
- int、char、double与byte相互转换
- [.NET]int 与 byte[] 的相互转换【转】
- int、char、double与byte相互转换
- int 与 byte[] 的相互转换
- java中int与byte〔4〕的相互转换
- int与byte数组相互转换
- byte[]到short、int、long的相互转换
- NSData 与NSString,Byte数组,UIImage,int的相互转换