java基础数据的转换

来源:互联网 发布:逻辑推理软件 编辑:程序博客网 时间:2024/05/16 18:29

1,最近写socket网络通信项目遇见了byte数组需要转换为各种类型,和16进制字符串的互相转换,封装了一些简单的工具类,给大家分享分享

2,代码

 /**     * 16进制字符串转换为Byte数组     */    public static byte[] toByte(String hex) {        if (hex == null) {            return null;        }        try {            return Hex.decodeHex(hex.toCharArray());        } catch (DecoderException e) {            logger.warn("Hex string Decoder error!", e);            return null;        }    }    /**     * byte数组转换成十六进制字符串     */    public static String toHex(byte[] command) {        return new String(Hex.encodeHex(command)).toUpperCase();    }    public static byte[] short2Byte(short a) {        byte[] b = new byte[2];        b[0] = (byte) (a >> 8);        b[1] = (byte) (a);        return b;    }    public static short[] int2Short(int a) {        short[] b = new short[2];        b[0] = (short) (a >> 16);        b[1] = (short) (a);        return b;    }    public static int short2Int(short[] uids) {        return (((uids[0] & 0xffffffff) << 16) | (uids[1] & 0xffffffff));    }    public static short byte2Short(byte[] b) {        return (short) (((b[0] & 0xff) << 8) | (b[1] & 0xff));    }    public static byte[] intToByte(int i) {        byte[] bytes = new byte[4];        bytes[0] = (byte) ((i >> 24) & 0xFF);        bytes[1] = (byte) ((i >> 16) & 0xFF);        bytes[2] = (byte) ((i >> 8) & 0xFF);        bytes[3] = (byte) (i & 0xFF);        return bytes;    }    public static Integer byteToInt(byte[] bytes) {        if (bytes == null || bytes.length != 4) {            return null;        }        return (bytes[0] & 0xff) << 24 |                (bytes[1] & 0xff) << 16 |                (bytes[2] & 0xff) << 8 |                (bytes[3] & 0xff);    }

注意

    Hex此类为阿帕奇的工具类,需要 org.apache.commons
原创粉丝点击