Android Int和byte数组,double和byte数组的相互转化
/**
* 把int类型的数直接放到byte数组的某个位置
*
* @param x
* int类型的数
* @param bb
* 要放到哪个数组
* @param pos
* 数组的位置
*/
public static void int2Byte(int x, byte[] bb, int pos) {
bb[pos] = (byte) (x >> 24);
bb[pos + 1] = (byte) (x >> 16);
bb[pos + 2] = (byte) (x >> 8);
bb[pos + 3] = (byte) (x >> 0);
} /**
* 把int转换成byte数组
*
* @param 要转换的int值
* @return 返回的byte数组
*/
public static byte[] int2BytesArray(int n) {
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (n >> (24 - i * 8));
}
return b;
}/**
* 把byte数组转换成int类型
*
* @param 源byte数组
* @return 返回的int值
*/
public static int byteArray2Int(byte[] b) {
int a = (((int) b[0]) << 24) + (((int) b[1]) << 16) + (((int) b[2]) << 8) + b[3];
if (a < 0) {
a = a + 256;
}
return a;
}/**
* byte数组2个字节转换成int
*
* @param b
* byte数组
* @param p
* 从哪个位置开始的两个byte
* @return
*/
public static final int stou(byte[] b, int p) {
return btou(b[p]) * 256 + btou(b[p + 1]);
} /**
* 这个函数的意思是不是从byte数组的第p哥位置开始4个字节转换成int
*
* @param b
* 源byte数组
* @param p
* 数组的第几个位置开始
* @return 返回的int值
*/
public static final int itou(byte[] b, int p) {
return ((btou(b[p]) * 256 + btou(b[p + 1])) * 256 + btou(b[p + 2])) * 256 + btou(b[p + 3]);
} /**
* 防止byte的值超过127,超过了都会变成负数
*
* @param b
* @return
*/
public static final int btou(byte b) {
if (b >= 0)
return (b + 0);
else
return (256 + b);
}附:double和byte数组的相互转化
/**
* byte数组转double
*
* @param Array
* @param Pos
* @return
*/
public static double byteArrayToDouble(byte[] Array, int Pos) {
long accum = 0;
accum = Array[Pos + 0] & 0xFF;
accum |= (long) (Array[Pos + 1] & 0xFF) << 8;
accum |= (long) (Array[Pos + 2] & 0xFF) << 16;
accum |= (long) (Array[Pos + 3] & 0xFF) << 24;
accum |= (long) (Array[Pos + 4] & 0xFF) << 32;
accum |= (long) (Array[Pos + 5] & 0xFF) << 40;
accum |= (long) (Array[Pos + 6] & 0xFF) << 48;
accum |= (long) (Array[Pos + 7] & 0xFF) << 56;
return Double.longBitsToDouble(accum);
} /**
* double 转byte数组
*
* @param Value
* @return
*/
public static byte[] doubleToByteArray(double Value) {
long accum = Double.doubleToRawLongBits(Value);
byte[] byteRet = new byte[8];
byteRet[0] = (byte) (accum & 0xFF);
byteRet[1] = (byte) ((accum >> 8) & 0xFF);
byteRet[2] = (byte) ((accum >> 16) & 0xFF);
byteRet[3] = (byte) ((accum >> 24) & 0xFF);
byteRet[4] = (byte) ((accum >> 32) & 0xFF);
byteRet[5] = (byte) ((accum >> 40) & 0xFF);
byteRet[6] = (byte) ((accum >> 48) & 0xFF);
byteRet[7] = (byte) ((accum >> 56) & 0xFF);
return byteRet;
}声明:该文观点仅代表作者本人,牛骨文系教育信息发布平台,牛骨文仅提供信息存储空间服务。
