gpt4 book ai didi

Java 与 Objective-c UTF-8 编码

转载 作者:行者123 更新时间:2023-11-29 10:36:26 24 4
gpt4 key购买 nike

我需要将 java 代码转换为 objective-c,但我被困在字符串到字节数组的转换中。

在java中我有:

String Key="1234567890";
byte[] xKey = Key.getBytes();
System.out.println(Arrays.toString(xKey));

它打印:

[49, 50, 51, 52, 53, 54, 55, 56, 57, 48]

在 objective-c 中我有:

NSString *Key = @"1234567890";
(1) NSData * xKey = [key dataUsingEncoding:NSUTF8StringEncoding];
(2) NSLog(@"%@", xKey);

并打印:

<31323334 3536373839 30>

在 (1) 中我用过:

const char * xKey = [Key UTF8String];

在 (2) 中我使用了:

NSLog(@"%@s", xKey);

在 UTF-8 中 48 对应于 0。

最佳答案

String "1234567890" 的正确 UTF-8 编码形式只是其字符的代码,因为所有字符都使用 1 个字节进行编码(它们的代码小于127):

[49, 50, 51, 52, 53, 54, 55, 56, 57, 48]

注意:Arrays.toString(byte[])使用字节的十进制表示来构造数组的String表示。

如果你仔细观察,Objective-c 结果完全一样,只是以十六进制基数打印:

<31323334 3536373839 30>

0x31 = 49
0x32 = 50
...
0x30 = 48

顺便说一下 String.getBytes() 从 javadoc 引用:

Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array.

因此使用平台的默认编码,因此结果可能会因平台而异,因此始终建议说明您想要结果的编码,例如:

byte[] xKey = Key.getBytes(StandardCharsets.UTF_8);

关于Java 与 Objective-c UTF-8 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26788728/

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