将NSString转换为uint8_t [英] Converting NSString into uint8_t

查看:575
本文介绍了将NSString转换为uint8_t的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究Apple在证书,密钥和信任编程指南中提供的数据加密示例代码。加密/解密数据的示例代码考虑了uint8_t。然而,真实世界的应用程序将在NSString对象上执行此操作。我一直在尝试将NSString对象转换为uint8_t,但每次我都收到编译器警告。对于在各种论坛中给出的几乎相同问题的解决方案,似乎对我没有用。

I am working on data encryption sample code provided by Apple in the "Certificate, Key and Trust Programming guide". The sample code for encrypting/Decrypting data considers an uint8_t. However the real world application would be doing this on an NSString object. I have been trying to convert NSString object to uint8_t but everytime I get compiler warning. Solutions given for 'almost' same problems given in various forums, don't seem to work for me.

推荐答案

这是一个将任何字符串值转换为 uint8_t * 的示例。最简单的方法是将NSData的字节转换为uint8_t *。其他选项是分配内存并复制字节,但你仍然需要以某种方式跟踪长度。

Here is an example of turning any string value into a uint8_t*. The easiest way is to just cast the bytes of NSData as and uint8_t*. Other option is to allocate memory and copy the bytes but you will still need to track the length somehow.

NSData *someData = [@"SOME STRING VALUE" dataUsingEncoding:NSUTF8StringEncoding];
const void *bytes = [someData bytes];
int length = [someData length];

//Easy way
uint8_t *crypto_data = (uint8_t*)bytes;



可选方式



Optional way

//If you plan on using crypto_data as a class variable
// you will need to do a memcpy since the NSData someData
// will get autoreleased
crypto_data = malloc(length);
memcpy(crypto_data, bytes, length);
//work with crypto_data

//free crypto_data most likely in dealloc
free(crypto_data);

这篇关于将NSString转换为uint8_t的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆