Increasing Length of NSData

强颜欢笑 提交于 2021-02-07 19:54:46

问题


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.


回答1:


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];


来源:https://stackoverflow.com/questions/10871433/increasing-length-of-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!