欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

字符串与二进制字符流之间相互转换,JAVA

程序员文章站 2024-03-18 14:32:40
...
private static String[] PREFIX_POOL = {"0", "00", "000", "0000", "00000", "000000", "0000000", "00000000",
            "000000000", "0000000000", "00000000000", "000000000000",
            "0000000000000", "00000000000000", "000000000000000"
    };
 
    /**
     * 字符串转换成二进制流
     *
     * @param str 字符串
     * @return 二进制流
     */
    private static String toBinary(String str) {
        if (null == str || str.trim().length() == 0) {
            return null;
        }
 
        char[] strChar = str.toCharArray();
        StringBuilder result = new StringBuilder(strChar.length << 4);
        for (int i = 0; i < strChar.length; i++) {
            // 二进制ASCII码
            String s = Integer.toBinaryString(strChar[i]);
            // 补0
            if (s.length() < 16) {
                s = PREFIX_POOL[15 - s.length()].concat(s);
            }
 
            result.append(s);
        }
 
        return result.toString();
    }
 
    /**
     * 二进制流转换成字符串
     *
     * @param binaryString 二进制流
     * @return 字符串
     */
    private static String toString(String binaryString) {
        if (null == binaryString || binaryString.trim().length() == 0) {
            return null;
        }
 
        int len = binaryString.length();
        StringBuilder sb = new StringBuilder(len >> 4);
        int step = 16;
        for (int i = 0; i < len; i += step) {
            // 将ascll码强转成字符
            sb.append((char) (int) Integer.parseInt(binaryString.substring(i, i + step), 2));
        }
 
        return sb.toString();
    }