0

我写了一个简单的片段,我尝试在 char 数组中转换(也许)一个字节数组,反之亦然。网上有很多例子,但这对我来说是最简单的方法。我需要使用数组而不是字符串,因为它的内容是要管理的密码字段。

所以我问你,这个片段是否正确?

private static char[] fromByteToCharArrayConverter(byte[] byteArray){
    ByteBuffer buffer = ByteBuffer.wrap(byteArray);
    clearArray(byteArray);
    CharBuffer charBuffer = Charset.forName("UTF-8").decode(buffer);

    char[] charArray = new char[charBuffer.remaining()];
    charBuffer.get(charArray);  

    return charArray;
}

private static byte[] fromCharToByteArray(char[] charArray){
    CharBuffer charBuffer = CharBuffer.wrap(charArray);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);

    byte[] byteArray = new byte[byteBuffer.remaining()];
    byteBuffer.get(byteArray);

    return byteArray;
}

谢谢

4

1 回答 1

0

不,这(至少)由于以下原因不起作用:

ByteBuffer buffer = ByteBuffer.wrap(byteArray);  // Wrap the array
clearArray(byteArray);  // Clear the array -> ByteBuffer cleared too
于 2019-11-01T11:42:24.673 回答