Convert 4 bytes to int

Posted by Oscar Reyes on Stack Overflow See other posts from Stack Overflow or by Oscar Reyes
Published on 2010-03-04T22:41:32Z Indexed on 2010/05/15 14:14 UTC
Read the original article Hit count: 419

Filed under:
|

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 = // ??? 
}

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.

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

What's the idiom for this?

EDIT

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

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.

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

00000000 00000000 00000000 00000001
00000000 00000000 00000000 00000010

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

Would be -1

and

01111111 11111111 11111111 11111111

Would be Integer.MAX_VALUE ( 2147483647 )

© Stack Overflow or respective owner

Related posts about java

Related posts about data-conversion