您的位置:首页 > 编程语言 > Java开发

【java工具类】字节操作

2013-08-20 13:59 239 查看
public class ByteUtil {
   
    public static byte[] join(byte[] src,byte[] des){
        byte[] result = new byte[src.length + des.length];
        System.arraycopy(src, 0, result, 0, src.length);
        System.arraycopy(des, 0, result, src.length, des.length);
        return result;
    }
   
    public static byte[] BigToLittleOrLittleToBig(byte[] src){
        int lenght = src.length;
        byte[] ret = new byte[lenght];
        for(int i = lenght;i>0;i--){
            ret[i-1] = src[lenght-i];
        }
        return ret;
    }
    public static byte[] intToByteArray1(int i) {
        byte[] result = new byte[4];
        result[0] = (byte) ((i >> 24) & 0xFF);
        result[1] = (byte) ((i >> 16) & 0xFF);
        result[2] = (byte) ((i >> 8) & 0xFF);
        result[3] = (byte) (i & 0xFF);
        return result;
    }
    public static byte[] longToByteArray1(long i) {
        byte[] result = new byte[8];
        result[ 0] = (byte) (i >> 56);
        result[ 1] = (byte) (i >> 48);
        result[ 2] = (byte) (i >> 40);
        result[ 3] = (byte) (i >> 32);
        result[ 4] = (byte) (i >> 24);
        result[ 5] = (byte) (i >> 16);
        result[ 6] = (byte) (i >> 8);
        result[ 7] = (byte) (i >> 0);
        return result;
    }
    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (java.lang.Integer.toHexString(b
& 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs;
    }
    public static byte[] hex2byte(String str) { // 字符串转二进制
        if (str == null)
            return null;
        str = str.trim();
        int len = str.length();
        if (len == 0 || len % 2 != 0)
            return null;
        byte[] b = new byte[len / 2];
        try {
            for (int i = 0; i < str.length(); i += 2) {
                b[i / 2] = (byte) Integer
                        .decode("0x" + str.substring(i, i + 2)).intValue();
            }
            return b;
        } catch (Exception e) {
            return null;
        }
    }
   
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: