2013-03-06 61 views
0

我想弄清楚從文件中獲取數據的方式,並且我想將每4個字節存儲爲一個位集(32)。我真的不知道如何做到這一點。我曾經玩過將文件中的每個字節存儲在一個數組中,然後試圖將每4個字節轉換爲一個bitset,但我真的無法用頭部包圍我的頭。有關如何去做這件事的任何想法?將字節轉換爲位集

FileInputStream data = null; 
try 
{ 
    data = new FileInputStream(myFile); 
} 
catch (FileNotFoundException e) 
{ 
    e.printStackTrace(); 
} 
ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
byte[] b = new byte[1024]; 
int bytesRead; 
while ((bytesRead = data.read(b)) != -1) 
{ 
     bos.write(b, 0, bytesRead); 
} 
byte[] bytes = bos.toByteArray(); 
+0

顯示您嘗試存儲每個字節的代碼。 – 2013-03-06 14:53:00

+0

FileInputStream data = null; 嘗試{ \t data = new FileInputStream(myFile); (FileNotFoundException e){ } catch(FileNotFoundException e){ \t e.printStackTrace(); } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte [] b =新字節[1024]; int bytesRead; ((bytesRead = data.read(b))!= -1)bos.write(b,0,bytesRead); } byte [] bytes = bos.toByteArray(); – Karl 2013-03-06 15:00:31

+0

不發表評論。將您的代碼添加到問題中! – 2013-03-06 15:01:15

回答

0

好吧,你有你的字節數組。現在你必須將每個字節轉換爲一個bitset。

//Is number of bytes divisable by 4 
bool divisableByFour = bytes.length % 4 == 0; 

//Initialize BitSet array 
BitSet[] bitSetArray = new BitSet[bytes.length/4 + divisableByFour ? 0 : 1]; 

//Here you convert each 4 bytes to a BitSet 
//You will handle the last BitSet later. 
int i; 
for(i = 0; i < bitSetArray.length-1; i++) { 
    int bi = i*4; 
    bitSetArray[i] = BitSet.valueOf(new byte[] { bytes[bi], bytes[bi+1], bytes[bi+2], bytes[bi+3]}); 
} 

//Now handle the last BitSet. 
//You do it here there may remain less than 4 bytes for the last BitSet. 
byte[] lastBitSet = new byte[bytes.length - i*4]; 
for(int j = 0; j < lastBitSet.length; j++) { 
    lastBitSet[i] = bytes[i*4 + j] 
} 

//Put the last BitSet in your bitSetArray 
bitSetArray[i] = BitSet.valueOf(lastBitSet); 

我希望這適用於你,因爲我寫得很快,並沒有檢查它的工作原理。但是這給了你基本的想法,這是我一開始的目的。