我正在读取这样的二进制文件:
InputStream in = new FileInputStream( file );
byte[] buffer = new byte[1024];
while( ( in.read(buffer ) > -1 ) {
int a = // ???
}
我想要读取最多 4 个字节并从中创建一个 int 值,但是我不知道该怎么做。
我觉得我必须一次抓取 4 个字节,并执行一个“字节”操作(如 >> << >> & FF 和类似的东西)来创建新的 int
这个成语是什么?
编辑
哎呀,这结果有点复杂(解释一下)
我想要做的是,读取一个文件(可能是 ascii,二进制,没关系)并提取它可能具有的整数。
例如假设二进制内容(以 2 为底):
00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000010
整数表示应该是 1
, 2
对吧? :-/前 32 位为 1,其余 32 位为 2。
11111111 11111111 11111111 11111111
应该是 -1
和
01111111 11111111 11111111 11111111
将是 Integer.MAX_VALUE (2147483647)
最佳答案
ByteBuffer 具有此功能,并且能够处理小端和大端整数。
考虑这个例子:
// read the file into a byte array
File file = new File("file.bin");
FileInputStream fis = new FileInputStream(file);
byte [] arr = new byte[(int)file.length()];
fis.read(arr);
// create a byte buffer and wrap the array
ByteBuffer bb = ByteBuffer.wrap(arr);
// if the file uses little endian as apposed to network
// (big endian, Java's native) format,
// then set the byte order of the ByteBuffer
if(use_little_endian)
bb.order(ByteOrder.LITTLE_ENDIAN);
// read your integers using ByteBuffer's getInt().
// four bytes converted into an integer!
System.out.println(bb.getInt());
希望这会有所帮助。
关于java - 将 4 个字节转换为 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2383265/