幾種資料類型與byte轉換方式

來源:互聯網
上載者:User

[java, 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 ;}

[java, 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); }

[java, 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;    }

[java, 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;    }

[java, 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; }

[java, 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; }

[Java, byte轉float]

public static float byteToFloat(byte[] v){        ByteBuffer bb = ByteBuffer.wrap(v);        FloatBuffer fb = bb.asFloatBuffer();        return fb.get();}

[Java, 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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.