daniel_tu 发表于 2013-2-3 11:24:47

byte,int,char,double的相互转换(java)

//整数到字节数组的转换
  public static byte[] intToByte(int number) {
    int temp = number;
    byte[] b=new byte;
    for (int i=b.length-1;i>-1;i--){
      b = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位
      temp = temp >> 8;       //向右移8位
    }
    return b;
  }

  //字节数组到整数的转换
  public static int byteToInt(byte[] b) {
    int s = 0;
    for (int i = 0; i < 3; i++) {
      if (b >= 0)
        s = s + b;
      else


        s = s + 256 + b;
      s = s * 256;
    }
    if (b >= 0)       //最后一个之所以不乘,是因为可能会溢出
      s = s + b;
    else
      s = s + 256 + b;
    return s;
  }

  //字符到字节转换
  public static byte[] charToByte(char ch){
    int temp=(int)ch;
    byte[] b=new byte;
    for (int i=b.length-1;i>-1;i--){
      b = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位
      temp = temp >> 8;       //向右移8位
    }
    return b;
  }

  //字节到字符转换


  public static char byteToChar(byte[] b){
    int s=0;
    if(b>0)
      s+=b;
    else
      s+=256+b;
    s*=256;
    if(b>0)
      s+=b;
    else
      s+=256+b;
    char ch=(char)s;
    return ch;
  }

  //浮点到字节转换
  public static byte[] doubleToByte(double d){
    byte[] b=new byte;
    long l=Double.doubleToLongBits(d);
    for(int i=0;i<b.length;i++){
      b=new Long(l).byteValue();
      l=l>>8;


    }
    return b;
  }

  //字节到浮点转换
  public static double byteToDouble(byte[] b){
    long l;

    l=b;
    l&=0xff;
    l|=((long)b<<8);
    l&=0xffff;
    l|=((long)b<<16);
    l&=0xffffff;
    l|=((long)b<<24);
    l&=0xffffffffl;
    l|=((long)b<<32);
    l&=0xffffffffffl;

    l|=((long)b<<40);
    l&=0xffffffffffffl;
    l|=((long)b<<48);


    l|=((long)b<<56);
    return Double.longBitsToDouble(l);
  }
 
页: [1]
查看完整版本: byte,int,char,double的相互转换(java)