gpt4 book ai didi

java - 将 char 数组转换为字节数组并再次返回

转载 作者:IT老高 更新时间:2023-10-28 20:51:55 24 4
gpt4 key购买 nike

我希望在不创建中间 String 的情况下将 Java char 数组转换为字节数组,因为 char 数组包含密码。我查找了几种方法,但它们似乎都失败了:

char[] password = "password".toCharArray();

byte[] passwordBytes1 = new byte[password.length*2];
ByteBuffer.wrap(passwordBytes1).asCharBuffer().put(password);

byte[] passwordBytes2 = new byte[password.length*2];
for(int i=0; i<password.length; i++) {
passwordBytes2[2*i] = (byte) ((password[i]&0xFF00)>>8);
passwordBytes2[2*i+1] = (byte) (password[i]&0x00FF);
}

String passwordAsString = new String(password);
String passwordBytes1AsString = new String(passwordBytes1);
String passwordBytes2AsString = new String(passwordBytes2);

System.out.println(passwordAsString);
System.out.println(passwordBytes1AsString);
System.out.println(passwordBytes2AsString);
assertTrue(passwordAsString.equals(passwordBytes1) || passwordAsString.equals(passwordBytes2));

断言总是失败(而且,关键的是,当代码在生产中使用时,密码被拒绝),但打印语句打印出密码三次。为什么 passwordBytes1AsStringpasswordBytes2AsStringpasswordAsString 不同,但看起来相同?我错过了一个空终止符还是什么?我该怎么做才能使转换和取消转换工作?

最佳答案

char和byte之间的转换是字符集的编码和解码。我更喜欢在代码中尽可能的清楚。这并不意味着额外的代码量:

 Charset latin1Charset = Charset.forName("ISO-8859-1"); 
charBuffer = latin1Charset.decode(ByteBuffer.wrap(byteArray)); // also decode to String
byteBuffer = latin1Charset.encode(charBuffer); // also decode from String

旁白:

java.nio 类和 java.io Reader/Writer 类使用 ByteBuffer 和 CharBuffer(它们使用 byte[] 和 char[] 作为支持数组)。如果您直接使用这些类,通常更可取。但是,您始终可以这样做:

 byteArray = ByteBuffer.array();  byteBuffer = ByteBuffer.wrap(byteArray);  
byteBuffer.get(byteArray); charBuffer.put(charArray);
charArray = CharBuffer.array(); charBuffer = ByteBuffer.wrap(charArray);
charBuffer.get(charArray); charBuffer.put(charArray);

关于java - 将 char 数组转换为字节数组并再次返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4931854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com