Tom Reay
Tom Reay

Reputation: 153

NSString to uint8_t doesn't match

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!

Upvotes: 0

Views: 831

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185801

You're using strlen() to get the size of an NSData*. That's not going to work. The NSData* isn't NUL-terminated. So you're getting garbage on the end.

Don't use strlen(). Just ask the NSData* for its size directly.

Alternatively, don't use NSData* at all and just ask for [key UTF8String]. That hands back a NUL-terminated const char *.

Upvotes: 3

Related Questions