熱點推薦:
您现在的位置: 電腦知識網 >> 編程 >> Java編程 >> JSP教程 >> 正文

int、char、double與byte相互轉換的程序

2013-11-15 11:50:59  來源: JSP教程 

  intchardouble與byte相互轉換的程序
  //整數到字節數組的轉換
   public static byte[] intToByte(int number) {
    int temp = number;
    byte[] b=new byte[];
    for (int i=blength;i>;i){
     b[i] = new Integer(temp&xff)bytevalue();   //將最高位保存在最低位
     temp = temp >> ;    //向右移
    }
    return b;
   }
  
   //字節數組到整數的轉換
   public static int byteToInt(byte[] b) {
    int s = ;
    for (int i = ; i < ; i++) {
     if (b[i] >= )
      s = s + b[i];
     else
  
  
      s = s + + b[i];
     s = s * ;
    }
    if (b[] >= )    //最後一個之所以不乘是因為可能會溢出
     s = s + b[];
    else
     s = s + + b[];
    return s;
   }
  
   //字符到字節轉換
   public static byte[] charToByte(char ch){
    int temp=(int)ch;
    byte[] b=new byte[];
    for (int i=blength;i>;i){
     b[i] = new Integer(temp&xff)bytevalue();   //將最高位保存在最低位
     temp = temp >> ;    //向右移
    }
    return b;
   }
  
   //字節到字符轉換
  
   public static char byteToChar(byte[] b){
    int s=;
    if(b[]>)
     s+=b[];
    else
     s+=+b[];
    s*=;
    if(b[]>)
     s+=b[];
    else
     s+=+b[];
    char ch=(char)s;
    return ch;
   }
  
   //浮點到字節轉換
   public static byte[] doubleToByte(double d){
    byte[] b=new byte[];
    long l=DoubledoubleToLongBits(d);
    for(int i=;ilength;i++){
     b[i]=new Long(l)bytevalue();
     l=l>>;
  
    }
    return b;
   }
  
   //字節到浮點轉換
   public static double byteToDouble(byte[] b){
    long l;
  
    l=b[];
    l&=xff;
    l|=((long)b[]<<);
    l&=xffff;
    l|=((long)b[]<<);
    l&=xffffff;
    l|=((long)b[]<<);
    l&=xffffffffl;
    l|=((long)b[]<<);
    l&=xffffffffffl;
  
    l|=((long)b[]<<);
    l&=xffffffffffffl;
    l|=((long)b[]<<48);
  
  
    l|=((long)b[7]<<56);
    return Double.longBitsToDouble(l);
   }
  
  --
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19749.html
    推薦文章
    Copyright © 2005-2013 電腦知識網 Computer Knowledge   All rights reserved.