2013-03-06 99 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); 

我希望这适用于你,因为我写得很快,并没有检查它的工作原理。但是这给了你基本的想法,这是我一开始的目的。