NSData的长度增加 [英] Increasing Length of NSData
问题描述
基本上,我有一个46个字符的NSString,可以将其转换为NSData.我需要将字符串填充为48个字符.仅通过在NSString的末尾添加''不能正常工作.因此,我只是使用以下方法增加了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);
称为'd'的NSData返回<723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32>
The NSData called 'd' returns <723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32>
称为'data'的NSData返回< 723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32_ >,其中_ 是4个随机字符(通常为数字)
The NSData called 'data' returns <723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f32_>, where _ is 4 random characters (usually numbers)
我如何确保'data'返回< 723d6c67 6e267573 65726e61 6d653d64 61766964 77617473 6f6e3936 26706173 73776f72 643d736e 30307079 6f320000>-4个0,而不是4个随机字符?
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?
谢谢.
推荐答案
您要使用NSMutableData,它是从字符串返回的NSData中创建的,然后添加一些零:
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];
这篇关于NSData的长度增加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!