生成随机二进制数据,如23ABFF

时间:2013-05-16 12:33:39

标签: java random types

我想生成类似于OData二进制的二进制数据,我不知道如何。 类型定义为

Represent fixed- or variable- length binary data
binary'[A-Fa-f0-9][A-Fa-f0-9]*' OR X '[A-Fa-f0-9][A-Fa-f0-9]*' NOTE: X and binary are case sensitive. Spaces are not allowed between binary and the quoted portion. Spaces are not allowed between X and the quoted portion. Odd pairs of hex digits are not allowed.

**Example 1: X'23AB' Example 2: binary'23ABFF'**

with next.random()我不确定哪种类型是合适的。 任何想法?

1 个答案:

答案 0 :(得分:1)

new Random().nextBytes(byte[])

编辑:您也可以使用

实现此目的
new Random().nextInt(16)

请参阅:

int nbDigitsYouWant=8;
Random r=new Random();
for(int i=0;i<nbDigitsYouWant;i++){
  //display hexa representation
  System.out.print(String.format("%x",r.nextInt(16)));
}

输出:

ea0d3b9d

编辑:这是一个快速而又脏的示例,其中随机字节发送到DataOutputStream。

public static void main(String[] args) throws Exception{
  DataOutputStream dos=new DataOutputStream(new FileOutputStream("/path/to/your/file"));

  int nbDesiredBytes=99999999;
  int bufferSize=1024;
  byte[] buffer = new byte[bufferSize];
  Random r=new Random();

  int nbBytes=0;
  while(nbBytes<nbDesiredBytes){
    int nbBytesToWrite=Math.min(nbDesiredBytes-nbBytes,bufferSize);
    byte[] bytes=new byte[nbBytesToWrite];
    r.nextBytes(bytes);
    dos.write(bytes);
    nbBytes+=nbBytesToWrite;
  }

  dos.close();
}