开发者

Converting NSString into uint8_t

开发者 https://www.devze.com 2023-02-06 04:39 出处:网络
I am working on data encryption sample code provided by Apple in the \"Certifica开发者_如何学编程te, Key and Trust Programming guide\". The sample code for encrypting/decrypting data considers an uint

I am working on data encryption sample code provided by Apple in the "Certifica开发者_如何学编程te, 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 every-time I try I get a compiler warning. Solutions given for 'almost' same problems given in various forums, don't seem to work for me.


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 *stringToEncrypt = @"SOME STRING VALUE";
uint8_t *cString = (uint8_t *)stringToEncrypt.UTF8String;
0

精彩评论

暂无评论...
验证码 换一张
取 消