2014-11-09 87 views
4

我有一個返回n個隨機字節的函數。爲了測試,我希望它產生4個隨機字節,然後將整數的4個字節分配爲隨機字節。我有一些工作,但它似乎是我嘗試做的過多的語法。我只是想看看它是否真的有必要,或者如果它能夠以更好的方式來完成將4個字符解釋爲整數

注意:這是在xv6正在做,沒有解決方案,涉及的include

int val0 = (((int)buf[0])&0xff); 
int val1 = (((int)buf[1])&0xff); 
int val2 = (((int)buf[2])&0xff); 
int val3 = (((int)buf[3])&0xff); 

int number = val0 | (val1<<8) | (val2<<16) | (val3<<24); 
+0

請注意,這是交換字節順序。 buf [0]從最高有效字節到最低有效字節。 – 2014-11-09 03:55:06

+0

@ D'Nabre,沒有注意到,字節是隨機的,但好點 – asimes 2014-11-09 03:58:44

+3

@ D'Nabre:在某些機器上,它不會交換字節序。 – 2014-11-09 04:10:37

回答

4

據我可以看到你正在使用gcc從這個reference here我們知道gcc support type punning through unions explicitly那麼這可能是一個合理的解決方案:

union charToInt 
{ 
    char arr[sizeof(int)] ; 
    int x ; 
} ; 

int main() 
{ 
    union charToInt u1 = { .arr = "ab" } ; // or { .arr = "abcd" } if sizeof(int) == 4 
} 

Then u1.x將保存int值。我沒有添加任何輸出,因爲我不確定輸出的用途。

+0

太好了,謝謝。我從來沒有好的理由在 – asimes 2014-11-09 03:56:49

+0

@asimes之前使用聯合,另一個主要用途是實現變體類型。 – 2014-11-09 04:02:08