[問題] DataInputStream: binary 轉 int(已解決)

作者: moers (MOラブリ~)   2015-04-27 19:36:51
各位前輩大大好
因為最近要做binary format 轉成 一般ascii format而遇到一些問題
輸入檔是序列合成資料全都是用binary表示int,其說明:
* Binary
The file is in the binary format.
The items in an itemset are displayed in increasing order,
then followed by a -1, which is the itemset delimiter.
When all the itemsets in a sequence are output,
follows a -2 as the sequence delimiter.
Then starts a new sequence.
-1當間隔,-2當換行,其他都是數字表示item
然而我卻在轉檔地方卡住,我用DataInputStream的readInt()讀取,
以下是我程式碼:
DataInputStream br = new DataInputStream(new FileInputStream(args[0]));
FileWriter writer = new FileWriter(args[0] + "aspmf");
int intRead;
while (br.available() > 0) {
intRead = br.readInt();
if (intRead != -2)
writer.write(intRead + " ");
else
writer.write("-2\n");
}
然而輸出黨卻是失敗的:
285212672 385875968 -1 -16777217 50331648 285212672 402653184 -1 33554432
83886080 100663296 134217728 285212672 335544320 369098752 -1 0 1342177 28
167772160 285212672 -1 -16777217 402653184 -1 -16777217 33554432 83886080
100663296 285212672 -1 16777216 33554432 134217728 285212672 3187671 04
369098752 385875968 402653184 -1 33554432 -1 0 83886080 134217728 -1 -16777217
讀的數量沒錯但是轉成int只有-1跟0是轉正確的
後來改用byte[]一次讀四個再轉int就沒有問題
// DataInputStream br = new DataInputStream(new FileInputStream(args[0]));
FileInputStream br = new FileInputStream(args[0]);
FileWriter writer = new FileWriter(args[0] + "aspmf");
byte[] buf = new byte[4];
int intRead;
while (br.available() > 0) {
br.read(buf);
intRead = convertirOctetEnEntier(buf);
//intRead = br.readInt();
if (intRead != -2)
writer.write(intRead + " ");
else
writer.write("-2\n");
[B}
//這是直接用網路上的,應該是正確的
public static int convertirOctetEnEntier(byte[] b){
int MASK = 0xFF;
int result = 0;
result = b[0] & MASK;
result = result + ((b[1] & MASK) << 8);
result = result + ((b[2] & MASK) << 16);
result = result + ((b[3] & MASK) << 24);
return result;
}
輸出結果:
17 23 -1 -2
3 17 24 -1 2 5 6 8 17 20 22 -1 0 8 10 17 -1 -2
24 -1 -2
2 5 6 17 -1 1 2 8 17 19 22 23 24 -1 2 -1 0 5 8 -1 -2
java api說明文件
DataInputStream readInt()
Returns:
the next four bytes of this input stream, interpreted as an int.
應該是要輸出一樣的東西,還是我對功能有所誤解?
附上完整程式碼還有輸入檔
http://git.io/vf9Q6 (點Raw可下載)
http://git.io/vf97n
感謝
作者: ssccg (23)   2015-04-27 19:44:00
java的readInt是big endian,看起來你資料是little endian
作者: moers (MOラブリ~)   2015-04-27 19:52:00
原來如此,太感謝了!

Links booklink

Contact Us: admin [ a t ] ucptt.com