将4个字节转换为int [英] Convert 4 bytes to int

查看:435
本文介绍了将4个字节转换为int的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm reading a binary file like this:

InputStream in = new FileInputStream( file );
byte[] buffer = new byte[1024];
while( ( in.read(buffer ) > -1 ) {

   int a = // ??? 
}

我想做什么来读取最多4个字节并从那些创建一个int值,但是,我不知道该怎么做。

What I want to do it to read up to 4 bytes and create a int value from those but, I don't know how to do it.

我觉得我必须一次抓取4个字节,并执行一个字节操作(如>><< >>& FF这样的东西)来创建新的int

I kind of feel like I have to grab 4 bytes at a time, and perform one "byte" operation ( like >> << >> & FF and stuff like that ) to create the new int

这是什么成语?

编辑

哎呀这个结果有点复杂(解释)

Ooops this turn out to be a bit more complex ( to explain )

我是什么我试图做的是,读取一个文件(可能是ascii,二进制,没关系)并提取它可能有的整数。

What I'm trying to do is, read a file ( may be ascii, binary, it doesn't matter ) and extract the integers it may have.

例如假设二进制内容(在基数2中):

For instance suppose the binary content ( in base 2 ) :

00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000010

整数表示应为 1 2 对吗? : - / 1表示前32位,2表示剩余的32位。

The integer representation should be 1 , 2 right? :- / 1 for the first 32 bits, and 2 for the remaining 32 bits.

11111111 11111111 11111111 11111111

将是-1

01111111 11111111 11111111 11111111

将是 Integer.MAX_VALUE(2147483647)

推荐答案

ByteBuffer具有此功能,并且能够处理小端和大端整数。

ByteBuffer has this capability, and is able to work with both little and big endian integers.

考虑这个例子:



//  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());

希望这有帮助。

这篇关于将4个字节转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆