2013-05-16 42 views
0

我想生成類似於OData二進制的二進制數據,我不知道如何。 類型被定義爲生成隨機二進制數據,如23ABFF

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'** 

與next.random()Im不肯定,其類型可以是適當的。 有什麼想法?

+0

是否將隨機int轉換爲十六進制選項?這可能不是最好的,但可能是一種選擇。 – Bill

回答

1
new Random().nextBytes(byte[]) 

編輯:

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 

ED你也可以用

new Random().nextInt(16) 

見做到這一點IT:這是一個快速和骯髒的例子,隨機字節發送到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(); 
} 
+0

謝謝你,我需要返回二進制值,所以應該是什麼樣的java類型,我沒有看到你在哪裏定義模型中的二進制類型... –

+0

然後字節或字節[]是最好的類型。我用一個快速而骯髒的示例更新了帖子,爲DataOutputStream生成隨機字節。 –