I’m trying to convert an NSString to uint8_t. The problem I’m having is that the NSString and the resulting uint8_t variables do not match. Here is some example code:
NSLog(@"Key now: %@", key);
NSData* keyData = [key dataUsingEncoding:NSUTF8StringEncoding];
const uint8_t *plainBuffer = (const uint8_t*)[data bytes];
size_t plainBufferSize = strlen((char *) plainBuffer);
NSLog(@"Plain buffer: %s", plainBuffer);
NSData* testData = [[NSData alloc] initWithBytes: plainBuffer length:plainBufferSize];
NSString* testString = [[NSString alloc] initWithData: testData encoding: NSUTF8StringEncoding];
NSLog(@"Test string: %@", testString);
And example output:
Key now: 9iIWBpf5R6yu5pJ93l218RsMdWBLidXt
Plain buffer: 9iIWBpf5R6yu5pJ93l218RsMdWBLidXtMdWBLidXt
Test string: 9iIWBpf5R6yu5pJ93l218RsMdWBLidXtMdWBLidXt
Clearly its the NSData -> uint8_t step thats going wrong, but I don’t know why!
You’re using
strlen()to get the size of anNSData*. That’s not going to work. TheNSData*isn’t NUL-terminated. So you’re getting garbage on the end.Don’t use
strlen(). Just ask theNSData*for its size directly.Alternatively, don’t use
NSData*at all and just ask for[key UTF8String]. That hands back a NUL-terminatedconst char *.