java - 将 4 个字节转换为 int

标签 java data-conversion

我正在读取这样的二进制文件:

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/

相关文章:

java - 在日历对象上向前/向后滚动几个月 (JAVA)

json - 如何使用 pl/pgsql 将具有动态元素名称的 JSON 数据转换为行?

java - 捕获 OutOfMemoryError 但不增加堆大小

java - linux 中的 update-alternatives 命令是什么,它有什么用?

c++ - 将wav编码为ogg vorbis时出现问题

javascript - 从 json 字符串创建可下载的 csv

java - 使用字符串和基数 2 - 36 进行 BaseConversion

c# - 如何在一个字节中转换 bool 数组,然后再转换回 bool 数组

java - 如何使 java 6 兼容 Kafka?

java - 在 JFreeChart 条形图中更改条形颜色