字节工具

来源:互联网 发布:nodejs 连接数据库 编辑:程序博客网 时间:2024/05/21 17:23
public class BytesUtil {    public static char[] hex = "0123456789ABCDEF".toCharArray();    public String bytesToHexStr(byte... bytes) {        char[] result = new char[bytes.length * 2];        for (int i = 0; i < bytes.length; i++) {            result[i] = hex[(bytes[i] >> 4) & 0x0F];            result[i + 1] = hex[bytes[i] & 0x0F];        }        return new String(result);    }    public byte[] hexStrToBytes(String byteStr) {        if (byteStr == null) {            return null;        }        if (byteStr.length() % 2 != 0) {            throw new RuntimeException("byteStr长度不是偶数,没法转");        }        int resultLen = byteStr.length() / 2;        byte[] result = new byte[resultLen];        char h, l;        byte b;        byteStr = byteStr.toUpperCase();        for (int i = 0; i < resultLen; i++) {            h = byteStr.charAt(i);            if ('0' <= h && h <= '9') {                b = (byte) (0x0F0 & (h - '0'));            } else if ('A' <= h && h <= 'F') {                b = (byte) (0x0F0 & (h - 'A' + 10));            } else {                throw new RuntimeException("byteStr 的第" + i + "个字符 不在16进制范围中");            }            l = byteStr.charAt(i + 1);            if ('0' <= l && l <= '9') {                b |= (byte) (0x0F & (l - '0'));            } else if ('A' <= l && l <= 'F') {                b |= (byte) (0x0F & (l - 'A' + 10));            } else {                throw new RuntimeException("byteStr 的第" + (i + 1) + "个字符 不在16进制范围中");            }            result[i] = b;        }        return result;    }}
0 0
原创粉丝点击