使用特定长度的随机字节生成NSData对象的最佳方法? [英] Best way to generate NSData object with random bytes of a specific length?

查看:165
本文介绍了使用特定长度的随机字节生成NSData对象的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用dataWithBytes:length:创建一个特定大小的新NSData对象,那么创建输入字节(价值20 Mb)随机字符的最有效方法是什么,最好不要从文件中读取数据?我每次都需要一个特定大小的唯一缓冲区。

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, preferably without reading the data in from a file? I need a unique buffer of a specific size each time.

谢谢

推荐答案

你可以创建一个20 * 2 ^ 20b NSData 对象,然后用<$ c $为它添加一个随机的4字节整数20 * 2 ^ 20/4次C> arc4random()。我认为你需要包含 stdlib.h (通过在Objective-中生成随机数] C )。

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

这篇关于使用特定长度的随机字节生成NSData对象的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆