如何“连接” NSString 的字节及其长度在一起?

发布于 2024-12-27 19:12:13 字数 186 浏览 1 评论 0原文

我有一个具有一定长度 [LEN] 的 NSString [WORD]。我需要做的是从这个字符串中获取字节并将它们与短长度(2字节)放在一起,所以我会有[WORD] [LEN]。 例如 字符串“AB”在utf8十六进制中是4142。这个字符串的长度是2==>十六进制的 0002。 所以所有内容加在一起就是 41420002。如何将这些字节组合在一起?

I have a NSString [WORD] that has some length [LEN]. What i need to do is to get bytes from this string and put them together with length in short (2 bytes), so i would have [WORD] [LEN].
E.g.
String "AB" in utf8 HEX is 4142. Length of this string is 2==> 0002 in HEX.
So everything together is 41420002. How to get this bytes together?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等待圉鍢 2025-01-03 19:12:13

我认为这段代码可以满足您的要求。

NSString *myString = @"AB";
const char *chars = [myString UTF8String];

NSMutableString * result = [NSMutableString string];
for (int i=0; i < [myString length]; i++) {
    [result appendFormat:@"%X", chars[i]];
}

[result appendFormat:@"%04X", [myString length]];

NSLog(@"%@", result);

希望有帮助!

I think this code does what you want.

NSString *myString = @"AB";
const char *chars = [myString UTF8String];

NSMutableString * result = [NSMutableString string];
for (int i=0; i < [myString length]; i++) {
    [result appendFormat:@"%X", chars[i]];
}

[result appendFormat:@"%04X", [myString length]];

NSLog(@"%@", result);

Hope it helps!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文