1. 程式人生 > >byte[] 與short、float、double的相互轉換

byte[] 與short、float、double的相互轉換

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;
	}
}