zl程序教程

您现在的位置是:首页 >  Java

当前栏目

java实现 byte数组与int ,float ,short 等类型进行相互转换

2023-02-25 18:17:25 时间

目录

1 byte字节数组转list

 public static List<Byte> bytesToList(byte[] bytes) {
    return Bytes.asList(bytes);
  }

2 list转byte字节数组

/**
   * list转字节组
   *
   * @param list list
   * @return byte[]
   */
  public static byte[] listToBytes(List<Byte> list) {
    return Bytes.toArray(list);
  }

3 截取bytes数组

/**
   * 截取bytes
   *
   * @param bytes 字节组
   * @param from 起始位
   * @param to 结束位
   * @return bytes
   */
  public static byte[] subBytes(byte[] bytes, int from, int to) {
    return Arrays.copyOfRange(bytes, from, to);
  }

4 byte[] 数组转short

    public static short bytes2Short(byte[] bytes) {
        short result=0;
        int len = bytes.length;
        for(int i=len-1;i>=0; i--){
            result |= (short)(i==0 ? bytes[i]:(bytes[i] & 0xff)) << ((len-1-i)<<3);
        }
        return result;
    }