问题:
bin文件如图,我们要读第一个字节的内容为 0xF0 实际读出来的结果为 -16
分析:
1. Java代码:返回值是 -16,看到这里发现没道理啊,为什么呢?
static String readBinFile(String name, int len) {
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ name;
File f = new File(path);
byte[] b = new byte[len];
String[] t = new String[len];
try {
FileInputStream fs = new FileInputStream(f);
int rl = fs.read(b);
if (rl != len)
Log.e("TOUCH", "read len:" + rl);
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
return b[0]+"";
}
2. 经调试发现返回值是0xFFF0,他的反码的补码正是-16
3. 也就是java读出来bin的值,默认长度是一个int类型,内存空间是2个byte,而我们要的是1个byte.
4. 看到这里就明白了,对这个读出来的值我们要进行简单处理,0xFFF0 & 0xFF = 0xF0
5. 这样就得到我们想要的结果了
解决方案:
完整代码如下:需要做一个byteToString的处理即可
private static void byteToString(byte[] b, String[] t) {
for (int i = 0; i < b.length; i++)
t[i] = String.format("%02X", (int) (b[i] & 0xFF));
}
static String readBinFile(String name, int len) {
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ name;
File f = new File(path);
byte[] b = new byte[len];
String[] t = new String[len];
try {
FileInputStream fs = new FileInputStream(f);
int rl = fs.read(b);
if (rl != len)
Log.e("TOUCH", "read len:" + rl);
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
byteToString(b, t);
return t[len - 1] + t[len - 2];
}