public class ShortFloatDoubleToByte {
/**
* double To byte[]
* @param d
* @return
*/
public static byte[] double2Bytes(double d) {
long value = Double.doubleToRawLongBits(d);
byte[] byteRet = new byte[8];
for (int i = 0; i < 8; i++) {
byteRet[i] = (byte) ((value >> 8 * i) & 0xff);
}
return byteRet;
}
/**
* byte[] To double
* @param arr
* @return
*/
public static double bytes2Double(byte[] arr) {
long value = 0;
for (int i = 0; i < 8; i++) {
value |= ((long) (arr[i] & 0xff)) << (8 * i);
}
return Double.longBitsToDouble(value);
}
//将一字节数据转换成二进制8bit字符串
public static String byteToBinaryStr(byte data){
String data5Str = new BigInteger(1,new byte[]{data}).toString(2);
while(data5Str.length()!=8){
data5Str="0"+data5Str;
}
return data5Str;
}
//二进制转换成十进制
public static int binaryToDecimal(String binarySource) {
BigInteger bi = new BigInteger(binarySource, 2); //转换为BigInteger类型
return Integer.parseInt(bi.toString()); //转换成十进制
}
//有符号整数
public static int byteToDecimalism(byte[] bytes){
String hex = ByteConvertUtil.bytes2HexString(bytes);
BigInteger bi = new BigInteger(hex, 16);
return bi.intValue();
}
public static byte[] float2byte(float f) {
// 把float转换为byte[]
int fbit = Float.floatToIntBits(f);
byte[] b = new byte[4];
for (int i = 0; i < 4; i++) {
b[i] = (byte) (fbit >> (24 - i * 8));
}
// 翻转数组
int len = b.length;
// 建立一个与源数组元素类型相同的数组
byte[] dest = new byte[len];
// 为了防止修改源数组,将源数组拷贝一份副本
System.arraycopy(b, 0, dest, 0, len);
byte temp;
// 将顺位第i个与倒数第i个交换
for (int i = 0; i < len / 2; ++i) {
temp = dest[i];
dest[i] = dest[len - i - 1];
dest[len - i - 1] = temp;
}
return dest;
}
//这个函数将byte转换成float
public static float byte2float(byte[] b) {
int l;
l = b[0];
l &= 0xff;
l |= ((long) b[1] << 8);
l &= 0xffff;
l |= ((long) b[2] << 16);
l &= 0xffffff;
l |= ((long) b[3] << 24);
return Float.intBitsToFloat(l);
}
public static byte[] short2Byte(short x){
byte high = (byte) (0x00FF & (x>>8)); //定义第一个byte
byte low = (byte) (0x00FF & x); //定义第二个byte
byte[] bytes = new byte[2];
bytes[0] = high;
bytes[1] = low;
return bytes;
}
public static short byte2Short(byte[] buf) {
short r = 0;
for (int i = 0; i < buf.length; i++) {
r <<= 8;
r |= (buf[i] & 0x00ff);
}
return r;
}
}