Converting NSString into uint8_t

后端 未结 2 995
春和景丽
春和景丽 2020-12-15 01:25

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 dat

相关标签:
2条回答
  • 2020-12-15 01:54

    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);
    
    0 讨论(0)
  • 2020-12-15 01:57
    NSString *stringToEncrypt = @"SOME STRING VALUE";
    uint8_t *cString = (uint8_t *)stringToEncrypt.UTF8String;
    
    0 讨论(0)
提交回复
热议问题