[问题] 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