Simon
Simon

Reputation: 67

Increasing Length of NSData

Basically, I have an NSString of 46 characters which i convert to NSData. I need to pad the string to 48 characters. It does not work via just adding ' ' to the end of the NSString. So, i just increased the length of NSData using this:

NSString *string = @"__46characterlongstring__";
NSData *d = [string dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"d: %@", d);
NSData *data = [NSData dataWithBytes:[d bytes] length:48];
NSLog(@"data: %@", data);

The NSData called 'd' returns <723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32>

The NSData called 'data' returns <723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32_>, where _ is 4 random characters (usually numbers)

How can i make sure that 'data' returns <723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f320000> - 4 0's instead of 4 random characters?

Thanks.

Upvotes: 3

Views: 2131

Answers (1)

Tom Andersen
Tom Andersen

Reputation: 7200

You want to use an NSMutableData, which you make from the NSData you get back from the string, then add some zeros:

NSMutableData *paddedData = [NSMutableData dataWithData:d];
[paddedData increaseLengthBy:4];

Upvotes: 8

Related Questions