Convert NSString to uint8_t

I am working on a sample data encryption code provided by Apple in the Certificate, Key, and Trust Programming Guide. Sample code for encrypting / decrypting data is considered as uint8_t. However, a real-world application will do this at the facility NSString. I tried to convert the object NSStringto uint8_t, but every time I try to get a compiler warning. The solutions suggested for "almost" the same problems in different forums do not seem to work for me.

+5
source share
2 answers

Here is an example of converting any string value to uint8_t*. The easiest way is to simply specify the bytes of NSData as and uint8_t *. Another option is to allocate memory and copy bytes, but you still need to somehow track the length.

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;

Additional 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);
+15
source
NSString *stringToEncrypt = @"SOME STRING VALUE";
uint8_t *cString = (uint8_t *)stringToEncrypt.UTF8String;
+2
source

All Articles