几种数据类型与byte转换方式

double 转 byte
public byte[] doubleToByte(double d) throws IOException {  
   double l = d ;  
   ByteArrayOutputStream baos = new ByteArrayOutputStream() ;  
   DataOutputStream dos = new DataOutputStream(baos) ;  
   dos.writeDouble(l) ;  
   byte b[] = baos.toByteArray() ;  
   return b ;  
}  
byte[] 转 double
public static double byteToDouble(byte[] b){  
    long 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);   
    l&=0xffffffffl;   
    l|=((long)b[4]<<32);   
    l&=0xffffffffffl;  
    l|=((long)b[5]<<40);   
    l&=0xffffffffffffl;   
    l|=((long)b[6]<<48);   
    l&=0xffffffffffffffl;   
    l|=((long)b[7]<<56);   
    return Double.longBitsToDouble(l);   
}  
int 转 byte]
public byte[] intToByte(int i) {  
        byte[] abyte0 = new byte[4];  
        abyte0[0] = (byte) (0xff & i);  
        abyte0[1] = (byte) ((0xff00 & i) >> 8);  
        abyte0[2] = (byte) ((0xff0000 & i) >> 16);  
        abyte0[3] = (byte) ((0xff000000 & i) >> 24);  
        return abyte0;  
    }  
byte 转 int
public  static int bytesToInt(byte[] bytes) {  
        int addr = bytes[0] & 0xFF;  
        addr |= ((bytes[1] << 8) & 0xFF00);  
        addr |= ((bytes[2] << 16) & 0xFF0000);  
        addr |= ((bytes[3] << 24) & 0xFF000000);  
        return addr;  
    }  
char 转 byte
public static byte[] charToByte(char ch){  
    int temp=(int)ch;   
    byte[] b=new byte[2];   
    for (int i=b.length-1;i>-1;i--){   
      b = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位   
      temp = temp >> 8;       //向右移8位   
    }   
    return b;   
}  
byte 转 char
public static char byteToChar(byte[] b){  
    int s=0;   
    if(b[0]>0)   
      s+=b[0];   
    else   
      s+=256+b[0];   
    s*=256;   
    if(b[1]>0)   
      s+=b[1];   
    else   
      s+=256+b[1];   
    char ch=(char)s;   
    return ch;   
}  
byte 转 float
public static float byteToFloat(byte[] v){  
        ByteBuffer bb = ByteBuffer.wrap(v);  
        FloatBuffer fb = bb.asFloatBuffer();  
        return fb.get();  
}  
float 转 byte
public static byte[] floatToByte(float v) {  
        ByteBuffer bb = ByteBuffer.allocate(4);  
        byte[] ret = new byte [4];  
        FloatBuffer fb = bb.asFloatBuffer();  
        fb.put(v);  
        bb.get(ret);  
        return ret;  
} 

Friskit

继续阅读此作者的更多文章