Java中char数组与byte数组的互转

        在加解密相关的实现时,有些方法用byte[],有些方法用char[],转来转去挺麻烦,所以提供两个转换函数。在网上查的,实现中碰到了问题,所以直接用字符串作为中间过渡。

char[] 转为byte[]:

   public static byte[] toBytes(char[] chars) {
        String s = new String(chars);
        return s.getBytes(StandardCharsets.UTF_8);
    }

 byte[] 转为 char[]:

    public static char[] toChars(byte[] bytes) {
        String s = new String(bytes, StandardCharsets.UTF_8);
        return s.toCharArray();
    }

使用以下方法,转中文时,在末尾会多出四个0,不清楚原因。

    public static byte[] getBytes(char[] chars) {
        Charset cs = Charset.forName("UTF-8");
        CharBuffer cb = CharBuffer.allocate(chars.length);
        cb.put(chars);
        cb.flip();
        ByteBuffer bb = cs.encode(cb);
        return bb.array();
    }

猜你喜欢

转载自blog.csdn.net/flyinmind/article/details/131330172