读取2进制文件应该是字节流
你可以试试下面的代码import java.io.*;public class ReadBytes {
public static void main(String[] arguments) {
try {
FileInputStream file = new
FileInputStream("class.dat");//class.dat文件名
boolean eof = false;
int count = 0;
while (!eof) {
int input = file.read();
System.out.print(input + " ");
if (input == -1)
eof = true;
else
count++;
}
file.close();
System.out.println("\nBytes read: " + count);
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
你可以试试下面的代码import java.io.*;public class ReadBytes {
public static void main(String[] arguments) {
try {
FileInputStream file = new
FileInputStream("class.dat");//class.dat文件名
boolean eof = false;
int count = 0;
while (!eof) {
int input = file.read();
System.out.print(input + " ");
if (input == -1)
eof = true;
else
count++;
}
file.close();
System.out.println("\nBytes read: " + count);
} catch (IOException e) {
System.out.println("Error -- " + e.toString());
}
}
}
int i1 = dataIn.readInt();
int i2 = dataIn.readInt();
float f = dataIn.readFloat();
float 型麻烦的多,如下: 31 23~30 0~22
┌───┬────┬───────┐
正负号│ 指数 │ 底数 │
└───┴────┴───────┘
正负号 (sign): 1 为负, 0 为正. 指数 (exponential): 將底数乘上 2 的指数次方后就是原來的数.
须注意的是: float 时, 因有 8 bits, 所以能表示的有 2 的
256 次方, 但因为指数应可正可负, 所以 IEEE 規定, 此处算
出的次方须減去 127 才是真的指数,所以 float 的指数可從
-126 到 128.
同理, double 型只有 11 bits, 算出的值须減去 1023, 所以
double 的指数可从 -1022 到 1024. 底数 (mantissa): 此部份格式实在难以用文字說明,
请参考下面的例子. < 特例 > 0 因为无法用任何 2 的次方表示, 所以 0 的表示法就是
float : 00 00 00 00 < 范例 > 將 17.625 换算成 float 型.
首先, 先將 17.625 换算成 2 进制: 10001.101
再來將 10001.101 向右 shift 直到小数点前只剩一位 (这一位
数当然是 1), 变成了 1.0001101 x 2 的 4 次方 (因为向右移了
4 位). 此时, 我们要的底数和指数就出來了: 底数部份,因为小
数点前必为 1, 所以 IEEE 规定只记录小数点后的就好, 所以
底数为 0001101 . 指数部份实际为 4, 但在格式中须加上
127 , 就是 131 , 即二進位的 10000011.
综合上列各项, 17.625 的 float 存储格式就是:
0 10000011 00011010000000000000000
换算成 byte : 41 8D 00 00
另外, 因为 INTEL CPU 是 little endian 的, 所以
41 8D 00 00 在内存中是按 00 00 8D 41 的顺序放的.
算法:(flnumstring:10001.101)
1.判断flnumstring字符串的有效性(7位 由1、0组成,只能出现一个小数点)(可选过程)
2.得到符号,如果是“-”则结果与0x80000000相或同时将“-”删除
3.对小数点进行移位操作:移位操作规则为保证小数点前只有1个有效数字,并且只能是1
例如:0.25->0.01为了满足上面的规则就需要向左移动两位(-2),而10001.101则需要向
右移动4位
4.分别求出指数以及底数
指数的计算可以通过判断小数点的移动位置判断
底数的计算可以在小数点移动完成后通过判断是”0”或“1”来处理
0.25的指数为-2+127=125(1111101) 底数为0 3E 80 00 00 (1111101 0000000)
10001.101的指数为131 底数的0001101
5.将指数与底数由结果相或(注意高低位)