Best way to generate NSData object with random bytes of a specific length?

后端 未结 9 1317
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 11:37

If I create a new NSData object of a specific size using dataWithBytes:length:, what is the most efficient way to create the input bytes (20 Mb worth) of random characters, pref

相关标签:
9条回答
  • 2021-02-05 12:16

    urandom is more efficient.

    Here is a category to generate random buffers:

    @interface NSMutableData(Random)
    +(id)randomDataWithLength:(NSUInteger)length;
    @end
    
    @implementation NSMutableData(Random)
    +(id)randomDataWithLength:(NSUInteger)length
    {
        NSMutableData* data=[NSMutableData dataWithLength:length];
        [[NSInputStream inputStreamWithFileAtPath:@"/dev/urandom"] read:(uint8_t*)[data mutableBytes] maxLength:length];
        return data;
    }
    @end
    
    0 讨论(0)
  • 2021-02-05 12:21

    The original version has a bug but mine takes care of that and hopefully doesn't introduce any new one. Hope it helps.

    - (NSData *)randomDataWithBytes: (NSUInteger)length {
        NSMutableData *mutableData = [NSMutableData dataWithCapacity: length];
        for (unsigned int i = 0; i < size; i++) { 
            NSInteger randomBits = arc4random();
            [mutableData appendBytes: (void *) &randomBits length: 1];
        } return mutableData;
    }
    

    Here is its unit test:

    NSInteger givenLength = INT16_MAX;
    NSData *randomData = [self randomDataWithBytes: givenLength];
    STAssertTrue([randomData length] == givenLength,
                 @"RandomDataWithBytes Failed Expected size %d and got %d", 
                 givenLength, [randomData length]);
    
    0 讨论(0)
  • 2021-02-05 12:23

    You can create a 20*2^20b NSData object, then append a random 4 byte integer to it 20*2^20/4 times with arc4random(). I believe you need to include stdlib.h (via Generating random numbers in Objective-C).

    #include <stdlib.h>
    
    -(NSData*)create20mbRandomNSData
    {
      int twentyMb           = 20971520;
      NSMutableData* theData = [NSMutableData dataWithCapacity:twentyMb];
      for( unsigned int i = 0 ; i < twentyMb/4 ; ++i )
      { 
        u_int32_t randomBits = arc4random();
        [theData appendBytes:(void*)&randomBits length:4];
      }
      return theData;
    }
    
    0 讨论(0)
提交回复
热议问题