int、char、与byte相互转换

来源:互联网 发布:中国穷人 知乎 编辑:程序博客网 时间:2024/06/05 06:42

//整数到字节数组的转换
  public static byte[] intToByte(int number) {
    int temp = number;
    byte[] b=new byte[4];
    for (int i=b.length-1;i>-1;i–){
      b[i] = 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[i] >= 0)
        s = s + b[i];
      else

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

  //字符到字节转换
  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[i] = new Integer(temp&0xff).byteValue();      //将最高位保存在最低位
      temp = temp >> 8;       //向右移8位
    }
    return b;
  }

  //字节到字符转换

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

 

 

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

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