将 NSString 转换为 Char 数组

发布于 2025-01-03 05:47:02 字数 320 浏览 3 评论 0原文

我有一个充满 NSString 的十六进制数组以及如何从中创建 char 数组。我不知道如何做到这一点。

所以我有一个数组

NSArray *myArray = [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];

,我想创建 ac char 数组,与此类似的

const unsigned char testing[] = { 0xAA, 0xBB, 0xCC };

任何建议将不胜感激

谢谢

I have an array full of NSString's in hex and what to create a char array from them. I'm not sure how this can be done.

So I have an array

NSArray *myArray = [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];

from this I want to create a c char array, something similar to this

const unsigned char testing[] = { 0xAA, 0xBB, 0xCC };

Any advice would be appreciated

Thanks

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

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

发布评论

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

评论(2

笑看君怀她人 2025-01-10 05:47:02

您可以采用 NSScaner 方法:

NSArray *myArray =
    [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];
int size = [myArray count];
unsigned char testing[size];

unsigned holder;

for (int i = 0; i < size; ++i) {
    [[NSScanner scannerWithString:[myArray objectAtIndex:i]]
                       scanHexInt:&holder];
    testing[i] = holder; /* or check for errors before assigning */
}

或 C 方法:

for (int i = 0; i < size; ++i) {
    sscanf([[myArray objectAtIndex:i] UTF8String], "%x", &holder);
    testing[i] = holder; /* same thing */
}

You can take the NSScaner approach:

NSArray *myArray =
    [NSArray arrayWithObjects:@"0xAA", @"0xBB", @"0xCC", nil];
int size = [myArray count];
unsigned char testing[size];

unsigned holder;

for (int i = 0; i < size; ++i) {
    [[NSScanner scannerWithString:[myArray objectAtIndex:i]]
                       scanHexInt:&holder];
    testing[i] = holder; /* or check for errors before assigning */
}

Or the C approach:

for (int i = 0; i < size; ++i) {
    sscanf([[myArray objectAtIndex:i] UTF8String], "%x", &holder);
    testing[i] = holder; /* same thing */
}
雄赳赳气昂昂 2025-01-10 05:47:02

使用 char test[] 定义了一个 char 数组。所以只能将一个字符串解析到该数组中。您必须定义

const unsigned char testing[][];

并在循环中填充它:

NSString *s = @"Some string";
const char *c = [s UTF8String];

using char testing[] you are defined an array of char. So just a string can be parsed into that array. You have to define

const unsigned char testing[][];

and in a loop fill it with this:

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