0

ファイルからデータを取得する方法を見つけようとしていますが、4 バイトごとにビットセット (32) として保存したいと考えています。これを行う方法が本当にわかりません。ファイルの各バイトを配列に格納してから、4バイトごとにビットセットに変換しようとしましたが、ビットセットを使用して頭を包み込むことはできません。これをどうやって進めるかについてのアイデアはありますか?

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(); 
4

1 に答える 1

0

わかりました、バイト配列を取得しました。次に、各バイトをビットセットに変換する必要があります。

//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);

私はすぐに書いたので、これがうまくいくことを願っています. しかし、これで基本的なアイデアが得られます。これは、当初の私の意図でした。

于 2013-03-06T17:43:31.253 に答える