java--byte

来源:互联网 发布:微信数据转移到sd卡 编辑:程序博客网 时间:2024/05/22 15:56
  1. byte在java中是一种是数据类型,代表一个字节,一个字节包含8个位,所以,byte类型的取值范围为-128到127;

  2. import java.nio.ByteBuffer;/** * author xander on  2017/9/7. * function 数据转换 */public final class UtilConvert {    private static ByteBuffer buffer = ByteBuffer.allocate(8);    //byte 与 int 的相互转换    public static byte intToByte(int x) {        return (byte) x;    }    public static int byteToInt(byte b) {        //Java 总是把 byte 当做有符处理;我们可以通过将其和 0xFF 进行二进制与得到它的无符值        return b & 0xFF;    }    //byte 数组与 int 的相互转换    public static int byteArrayToInt(byte[] b) {        return b[3] & 0xFF |                (b[2] & 0xFF) << 8 |                (b[1] & 0xFF) << 16 |                (b[0] & 0xFF) << 24;    }    /**     * @param a int转byte[]     * @return     */    public static byte[] intToByteArray(int a) {        return new byte[]{                (byte) ((a >> 24) & 0xFF),                (byte) ((a >> 16) & 0xFF),                (byte) ((a >> 8) & 0xFF),                (byte) (a & 0xFF)        };    }    //byte 数组与 long 的相互转换    public static byte[] longToBytes(long x) {        buffer.putLong(0, x);        return buffer.array();    }    public static long bytesToLong(byte[] bytes) {        buffer.put(bytes, 0, bytes.length);        buffer.flip();//need flip        return buffer.getLong();    }}