简体   繁体   English

我如何将NSString转换为uint8_t数组

[英]How can i convert NSString to uint8_t array

I have an NSString like so: 850210 我有一个NSString像这样:850210

How can i convert it to uint8_t data[]={0x85,0x02,0x10}; 如何将其转换为uint8_t数据[] = {0x85,0x02,0x10};

Could someone please help me out with this?? 有人可以帮我吗?

BR, Suppi BR,Suppi

#import <Foundation/Foundation.h>
static NSString * const hexString = @"850210";

int main (int argc, const char * argv[])
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    uint8_t         data[3]={0};
    const char      * theUniChar = hexString.UTF8String;

    for( int i = 0, c = (int)strlen(theUniChar)/2; i < c && i < sizeof(data)/sizeof(*data); i++ )
    {
        int     theNum = 0;
        sscanf( theUniChar + 2*i, "%2x", &theNum );
        data[i] = theNum;
    }

    printf( "{%x,%x,%x}\n", data[0],data[1],data[2] );


    [pool drain];
    return 0;
}

Loop over the string and start by checking for strings of length < 3. If it is just simply call intValue on the NSString itself and you have your first and only byte. 循环遍历字符串,然后检查长度小于3的字符串。如果只是简单地在NSString本身上调用intValue,则您将拥有第一个也是唯一的字节。

If it's larger than or equal to three start by reading in three numbers and checking if that is larger than 255. If it is re-read in the two bytes and check what value they have and that's a byte. 如果它大于或等于3,则先读取三个数字,然后检查该数字是否大于255。如果要重新读取两个字节,并检查它们的值,则为一个字节。 If it's not then take the three first numbers and that's a byte. 如果不是,则取前三个数字,即一个字节。

Repeat this process on the remaining string that you have (a string created by disregarding the numbers you have already read in). 对剩余的字符串(不考虑已读入的数字而创建的字符串)重复此过程。

Good luck :) 祝好运 :)


I was assuming that string was in decimal format. 我以为该字符串为十进制格式。 If that's hex then simply read in two numbers at a time. 如果是十六进制,则只需一次读取两个数字。 And use this question to help you: How can I convert hex number to integers and strings in Objective C? 并使用此问题来帮助您: 如何在目标C中将十六进制数转换为整数和字符串?


Second edit: 第二编辑:

I have not tested this but you if there are any errors they should be easy to fix: 我没有对此进行测试,但是您是否有任何错误应该很容易解决:

NSString *hexString = @"8510A0";
uint8_t *result = (uint8_t *)malloc(sizeof(uint8_t) * ([hexString length] / 2));
for(int i = 0; i < [hexString length]; i += 2) {
    NSRange range = { i, 2 };
    NSString *subString = [hexString subStringWithRange:range];
    unsigned value;
    [[NSScanner scannerWithString:subString] scanHexInt:&value];
    result[i / 2] = (uint8_t)value;
}
// result now contains what you want
free(result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM