IOS中怎么把NSString转成byte数组啊?像java中getBytes这样的

tingfengzheshuo 2015-09-09 02:55:08
项目中需要调用.c文件中的一个函数,像这样的
int32_t gpc_prep(uint8_t *input, uint32_t input_len, uint8_t *output, uint32_t output_len)
input和output在java中是两个byte数组,这是我之前做的android项目中的,现在移植到IOS中有一些小问题,input这个数组一个字符串转换成的byte数组,output用来接收一串数据的缓存。在java中input直接用String中的getBytes方法就得到了,IOS中怎么把NSString转成byte数组啊,看了系统里面的方法,有getBytes方法,但是自己试着用总是有问题啊,同样一个字符串,在java中的和xcode中调试得到的数组不一样
我尝试了几个方法
-(NSData *) NSString2Bytes{
NSMutableData *data = [NSMutableData data];
int idx;
for (idx = 0; idx + 2 <= self.length; idx += 2) {
NSRange range = NSMakeRange(idx, 2);
NSString *hexStr = [self substringWithRange:range];
NSScanner *scanner = [NSScanner scannerWithString:hexStr];
unsigned int intValue;
[scanner scanHexInt:&intValue];
[data appendBytes:&intValue length:1];
}
return data;
}
还有dataUsingncoding方法,感觉都不太好用啊。
请大神解答下怎么开辟一个byte数组做缓存啊,像C语言中的byte bufbyte[1024]好像有问题啊。
...全文
1304 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
LichKingSZ 2015-09-09
  • 打赏
  • 举报
回复

/**
 *	@brief	将字符表示的16进制数转化为二进制数据
 *
 *	@param 	hexString 	字符表示的16进制数,长度必须为偶数
 *
 *	@return	二进制数据
 */
- (NSData *)dataWithHexString:(NSString *)hexString
{
    // hexString的长度应为偶数
    if ([hexString length] % 2 != 0)
        return nil;
    
    NSUInteger len = [hexString length];
    NSMutableData *retData = [[[NSMutableData alloc] init] autorelease];
    const char *ch = [[hexString dataUsingEncoding:NSASCIIStringEncoding] bytes];
    for (int i=0 ; i<len ; i+=2) {
        
        int height=0;
        if (ch[i]>='0' && ch[i]<='9')
            height = ch[i] - '0';
        else if (ch[i]>='A' && ch[i]<='F')
            height = ch[i] - 'A' + 10;
        else if (ch[i]>='a' && ch[i]<='f')
            height = ch[i] - 'a' + 10;
        else
            // 错误数据
            return nil;
        
        int low=0;
        if (ch[i+1]>='0' && ch[i+1]<='9')
            low = ch[i+1] - '0';
        else if (ch[i+1]>='A' && ch[i+1]<='F')
            low = ch[i+1] - 'A' + 10;
        else if (ch[i+1]>='a' && ch[i+1]<='f')
            low = ch[i+1] - 'a' + 10;
        else
            // 错误数据
            return nil;
        
        int byteValue = height*16 + low;
        [retData appendBytes:&byteValue length:1];
    }
    
    return retData;
}

29,049

社区成员

发帖
与我相关
我的任务
社区描述
主要讨论与iOS相关的软件和技术
社区管理员
  • iOS
  • 大熊猫侯佩
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧