Convert 4 bytes to 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 = // ???
}
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 )
java data-conversion
add a comment |
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 )
java data-conversion
add a comment |
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 )
java data-conversion
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 )
java data-conversion
java data-conversion
edited Mar 5 '10 at 7:11
cletus
503k139838909
503k139838909
asked Mar 4 '10 at 22:41
OscarRyzOscarRyz
141k96336513
141k96336513
add a comment |
add a comment |
10 Answers
10
active
oldest
votes
ByteBuffer has this capability, and is able to work with both little and big endian integers.
Consider this example:
// 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());
Hope this helps.
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
add a comment |
You should put it into a function like this:
public static int toInt(byte bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte bytes = new byte{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use
readByte()
repeatedly and not worry about it otherwise;Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact% 4
bytes right?
– OscarRyz
Mar 4 '10 at 22:46
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
Thanks for the code snippet, i should point out a bug here -ret |= (int)bytes[i] & 0xFF;
should really beret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.
– Ying
Feb 9 '17 at 0:23
|
show 13 more comments
If you have them already in a byte array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
add a comment |
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
add a comment |
The easiest way is:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int i = in.readInt();
-- or --
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("filename")));
int i = in.readInt();
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
add a comment |
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translatex * 256
intox << 8
automatically.
– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use<<
, it's because of readability. By using<<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the+
s to|
s
– Justin
Jul 31 '14 at 23:26
add a comment |
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
add a comment |
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
add a comment |
For reading unsigned 4 bytes as integer we should use a long variable, because the sign bit is considered as part of the unsigned number.
long result = (((bytes[0] << 8 & bytes[1]) << 8 & bytes[2]) << 8) & bytes[3];
result = result & 0xFFFFFFFF;
This is tested well worked function
add a comment |
The following code reads 4 bytes from array
(a byte
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2383265%2fconvert-4-bytes-to-int%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
10 Answers
10
active
oldest
votes
10 Answers
10
active
oldest
votes
active
oldest
votes
active
oldest
votes
ByteBuffer has this capability, and is able to work with both little and big endian integers.
Consider this example:
// 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());
Hope this helps.
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
add a comment |
ByteBuffer has this capability, and is able to work with both little and big endian integers.
Consider this example:
// 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());
Hope this helps.
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
add a comment |
ByteBuffer has this capability, and is able to work with both little and big endian integers.
Consider this example:
// 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());
Hope this helps.
ByteBuffer has this capability, and is able to work with both little and big endian integers.
Consider this example:
// 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());
Hope this helps.
answered Mar 5 '10 at 0:25
TomTom
11.2k115668
11.2k115668
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
add a comment |
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
+1 See also stackoverflow.com/questions/2211927/…
– trashgod
Mar 5 '10 at 4:27
add a comment |
You should put it into a function like this:
public static int toInt(byte bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte bytes = new byte{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use
readByte()
repeatedly and not worry about it otherwise;Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact% 4
bytes right?
– OscarRyz
Mar 4 '10 at 22:46
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
Thanks for the code snippet, i should point out a bug here -ret |= (int)bytes[i] & 0xFF;
should really beret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.
– Ying
Feb 9 '17 at 0:23
|
show 13 more comments
You should put it into a function like this:
public static int toInt(byte bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte bytes = new byte{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use
readByte()
repeatedly and not worry about it otherwise;Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact% 4
bytes right?
– OscarRyz
Mar 4 '10 at 22:46
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
Thanks for the code snippet, i should point out a bug here -ret |= (int)bytes[i] & 0xFF;
should really beret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.
– Ying
Feb 9 '17 at 0:23
|
show 13 more comments
You should put it into a function like this:
public static int toInt(byte bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte bytes = new byte{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use
readByte()
repeatedly and not worry about it otherwise;Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
You should put it into a function like this:
public static int toInt(byte bytes, int offset) {
int ret = 0;
for (int i=0; i<4 && i+offset<bytes.length; i++) {
ret <<= 8;
ret |= (int)bytes[i] & 0xFF;
}
return ret;
}
Example:
byte bytes = new byte{-2, -4, -8, -16};
System.out.println(Integer.toBinaryString(toInt(bytes, 0)));
Output:
11111110111111001111100011110000
This takes care of running out of bytes and correctly handling negative byte values.
I'm unaware of a standard function for doing this.
Issues to consider:
Endianness: different CPU architectures put the bytes that make up an int in different orders. Depending on how you come up with the byte array to begin with you may have to worry about this; and
Buffering: if you grab 1024 bytes at a time and start a sequence at element 1022 you will hit the end of the buffer before you get 4 bytes. It's probably better to use some form of buffered input stream that does the buffered automatically so you can just use
readByte()
repeatedly and not worry about it otherwise;Trailing Buffer: the end of the input may be an uneven number of bytes (not a multiple of 4 specifically) depending on the source. But if you create the input to begin with and being a multiple of 4 is "guaranteed" (or at least a precondition) you may not need to concern yourself with it.
to further elaborate on the point of buffering, consider the BufferedInputStream
:
InputStream in = new BufferedInputStream(new FileInputStream(file), 1024);
Now you have an InputStream
that automatically buffers 1024 bytes at a time, which is a lot less awkward to deal with. This way you can happily read 4 bytes at a time and not worry about too much I/O.
Secondly you can also use DataInputStream
:
InputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream(file), 1024));
byte b = in.readByte();
or even:
int i = in.readInt();
and not worry about constructing int
s at all.
edited Mar 4 '10 at 23:44
answered Mar 4 '10 at 22:45
cletuscletus
503k139838909
503k139838909
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact% 4
bytes right?
– OscarRyz
Mar 4 '10 at 22:46
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
Thanks for the code snippet, i should point out a bug here -ret |= (int)bytes[i] & 0xFF;
should really beret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.
– Ying
Feb 9 '17 at 0:23
|
show 13 more comments
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact% 4
bytes right?
– OscarRyz
Mar 4 '10 at 22:46
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
Thanks for the code snippet, i should point out a bug here -ret |= (int)bytes[i] & 0xFF;
should really beret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.
– Ying
Feb 9 '17 at 0:23
1
1
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
+1, Watch out for endianness!
– Carl Norum
Mar 4 '10 at 22:45
I just have to consider the fact my array might not read exact
% 4
bytes right?– OscarRyz
Mar 4 '10 at 22:46
I just have to consider the fact my array might not read exact
% 4
bytes right?– OscarRyz
Mar 4 '10 at 22:46
3
3
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg
(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
One MAJOR problem with your code -- java's byte type is SIGNED, so if the top bit of any byte is set, your code will also set all the upper bits in the resulting int. You need to mask off the upper bits of each byte before shifting and oring, eg
(bytes[0] & 0xff) | ((bytes[1] & 0xff) << 8) | ...
– Chris Dodd
Mar 4 '10 at 23:19
1
1
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
I hate to say this, but your offset support is completely broken. See ideone.com/uCpovu, where I also have the fix.
– quantum
Dec 2 '12 at 21:10
1
1
Thanks for the code snippet, i should point out a bug here -
ret |= (int)bytes[i] & 0xFF;
should really be ret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.– Ying
Feb 9 '17 at 0:23
Thanks for the code snippet, i should point out a bug here -
ret |= (int)bytes[i] & 0xFF;
should really be ret |= (int)bytes[i + offset] & 0xFF;
- otherwise the offset param is ignored completely.– Ying
Feb 9 '17 at 0:23
|
show 13 more comments
If you have them already in a byte array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
add a comment |
If you have them already in a byte array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
add a comment |
If you have them already in a byte array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
If you have them already in a byte array, you can use:
int result = ByteBuffer.wrap(bytes).getInt();
source: here
edited May 23 '17 at 12:18
Community♦
11
11
answered May 15 '10 at 14:08
iTEggiTEgg
3,4341864103
3,4341864103
add a comment |
add a comment |
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
add a comment |
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
add a comment |
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
answered Mar 5 '10 at 10:52
Santhosh Kumar TekuriSanthosh Kumar Tekuri
2,4351619
2,4351619
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
add a comment |
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
7
7
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It should be noted that this is for big-endian ordered bytes, where as support for little only takes a small change: return ((ch4 << 24) + (ch3 << 16) + (ch2 << 8) + (ch1 << 0));
– Paul Gregoire
Sep 16 '11 at 20:57
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
It is no correct. E.g., if 4th byte equals -1, and others are 0, your result is -1, but should be 255. int k = ((byte)-1) << 0; System.err.println(k); // -1
– Mikhail Ionkin
Mar 18 '18 at 14:51
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@MikhailIonkin Your comment is wrong, and this code is correct. in.read() does not return a byte. If it did, sign extension would occur when it was stored in an int variable. But in.read() returns the next byte of the stream converted to int WITHOUT sign extension. So If the next byte of the stream is 0xFF, in.read() would return 0x000000FF. The only way in.read() will return -1 is when you reach the end of the stream.
– Craig Parton
Aug 25 '18 at 13:21
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
@CraigParton yes, but question is how to convert 4 bytes, not 4 ints
– Mikhail Ionkin
Aug 26 '18 at 11:12
add a comment |
The easiest way is:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int i = in.readInt();
-- or --
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("filename")));
int i = in.readInt();
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
add a comment |
The easiest way is:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int i = in.readInt();
-- or --
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("filename")));
int i = in.readInt();
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
add a comment |
The easiest way is:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int i = in.readInt();
-- or --
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("filename")));
int i = in.readInt();
The easiest way is:
RandomAccessFile in = new RandomAccessFile("filename", "r");
int i = in.readInt();
-- or --
DataInputStream in = new DataInputStream(new BufferedInputStream(
new FileInputStream("filename")));
int i = in.readInt();
edited Mar 4 '10 at 23:09
answered Mar 4 '10 at 22:48
Taylor LeeseTaylor Leese
34.8k2496134
34.8k2496134
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
add a comment |
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
1
1
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
– stmax
Mar 4 '10 at 22:54
add a comment |
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translatex * 256
intox << 8
automatically.
– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use<<
, it's because of readability. By using<<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the+
s to|
s
– Justin
Jul 31 '14 at 23:26
add a comment |
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translatex * 256
intox << 8
automatically.
– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use<<
, it's because of readability. By using<<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the+
s to|
s
– Justin
Jul 31 '14 at 23:26
add a comment |
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
answered Mar 4 '10 at 22:46
stmaxstmax
4,46122138
4,46122138
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translatex * 256
intox << 8
automatically.
– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use<<
, it's because of readability. By using<<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the+
s to|
s
– Justin
Jul 31 '14 at 23:26
add a comment |
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translatex * 256
intox << 8
automatically.
– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use<<
, it's because of readability. By using<<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the+
s to|
s
– Justin
Jul 31 '14 at 23:26
2
2
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
+1 except you should use << instead of multiplication
– Andrey
Mar 4 '10 at 22:51
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
Although I conceptually agree with Andrey, I'd hope any descent compiler would figure that out and fix it for you. However, << IS clearer for this purpose.
– Bill K
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translate
x * 256
into x << 8
automatically.– cletus
Mar 4 '10 at 22:57
@Andrey: to be fair, the Java compiler will probably translate
x * 256
into x << 8
automatically.– cletus
Mar 4 '10 at 22:57
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
depends on quality of compiler :)
– Andrey
Mar 5 '10 at 10:49
It's not because of the "faster" code that you should use
<<
, it's because of readability. By using <<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the +
s to |
s– Justin
Jul 31 '14 at 23:26
It's not because of the "faster" code that you should use
<<
, it's because of readability. By using <<
, it is clear that we are doing bit operations rather than multiplication. In fact, I'd even change the +
s to |
s– Justin
Jul 31 '14 at 23:26
add a comment |
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
add a comment |
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
add a comment |
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
for (int i = 0; i < buffer.length; i++)
{
a = (a << 8) | buffer[i];
if (i % 3 == 0)
{
//a is ready
a = 0;
}
}
answered Mar 4 '10 at 22:49
AndreyAndrey
51.3k993144
51.3k993144
add a comment |
add a comment |
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
add a comment |
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
add a comment |
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
You can also use BigInteger for variable length bytes. You can convert it to Long, Integer or Short, whichever suits your needs.
new BigInteger(bytes).intValue();
or to denote polarity:
new BigInteger(1, bytes).intValue();
answered Jul 31 '13 at 20:36
Jamel TomsJamel Toms
3,14222024
3,14222024
add a comment |
add a comment |
For reading unsigned 4 bytes as integer we should use a long variable, because the sign bit is considered as part of the unsigned number.
long result = (((bytes[0] << 8 & bytes[1]) << 8 & bytes[2]) << 8) & bytes[3];
result = result & 0xFFFFFFFF;
This is tested well worked function
add a comment |
For reading unsigned 4 bytes as integer we should use a long variable, because the sign bit is considered as part of the unsigned number.
long result = (((bytes[0] << 8 & bytes[1]) << 8 & bytes[2]) << 8) & bytes[3];
result = result & 0xFFFFFFFF;
This is tested well worked function
add a comment |
For reading unsigned 4 bytes as integer we should use a long variable, because the sign bit is considered as part of the unsigned number.
long result = (((bytes[0] << 8 & bytes[1]) << 8 & bytes[2]) << 8) & bytes[3];
result = result & 0xFFFFFFFF;
This is tested well worked function
For reading unsigned 4 bytes as integer we should use a long variable, because the sign bit is considered as part of the unsigned number.
long result = (((bytes[0] << 8 & bytes[1]) << 8 & bytes[2]) << 8) & bytes[3];
result = result & 0xFFFFFFFF;
This is tested well worked function
answered Apr 7 '18 at 5:52
MounirMounir
1
1
add a comment |
add a comment |
The following code reads 4 bytes from array
(a byte
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
add a comment |
The following code reads 4 bytes from array
(a byte
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
add a comment |
The following code reads 4 bytes from array
(a byte
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
The following code reads 4 bytes from array
(a byte
) at position index
and returns a int
. I tried out most of the code from the other answers on Java 10 and some other variants I dreamed up.
This code used the least amount of CPU time but allocates a ByteBuffer
until Java 10's JIT gets rid of the allocation.
int result;
result = ByteBuffer.
wrap(array).
getInt(index);
This code is the best performing code that does not allocate anything. Unfortunately, it consumes 56% more CPU time compared to the above code.
int result;
short data0, data1, data2, data3;
data0 = (short) (array[index++] & 0x00FF);
data1 = (short) (array[index++] & 0x00FF);
data2 = (short) (array[index++] & 0x00FF);
data3 = (short) (array[index++] & 0x00FF);
result = (data0 << 24) | (data1 << 16) | (data2 << 8) | data3;
edited Nov 23 '18 at 18:46
answered Nov 23 '18 at 18:39
NathanNathan
3,41052751
3,41052751
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2383265%2fconvert-4-bytes-to-int%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown