Convert 4 bytes to int












65














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 )










share|improve this question





























    65














    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 )










    share|improve this question



























      65












      65








      65


      22





      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 )










      share|improve this question















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 5 '10 at 7:11









      cletus

      503k139838909




      503k139838909










      asked Mar 4 '10 at 22:41









      OscarRyzOscarRyz

      141k96336513




      141k96336513
























          10 Answers
          10






          active

          oldest

          votes


















          65














          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.






          share|improve this answer





















          • +1 See also stackoverflow.com/questions/2211927/…
            – trashgod
            Mar 5 '10 at 4:27



















          27














          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:




          1. 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


          2. 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;


          3. 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 ints at all.






          share|improve this answer



















          • 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 be ret |= (int)bytes[i + offset] & 0xFF; - otherwise the offset param is ignored completely.
            – Ying
            Feb 9 '17 at 0:23



















          26














          If you have them already in a byte array, you can use:



          int result = ByteBuffer.wrap(bytes).getInt();


          source: here






          share|improve this answer































            14














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





            share|improve this answer

















            • 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





















            5














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





            share|improve this answer



















            • 1




              assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
              – stmax
              Mar 4 '10 at 22:54



















            4














            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.






            share|improve this answer

















            • 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 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










            • 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



















            1














            for (int i = 0; i < buffer.length; i++)
            {
            a = (a << 8) | buffer[i];
            if (i % 3 == 0)
            {
            //a is ready
            a = 0;
            }
            }





            share|improve this answer





























              1














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





              share|improve this answer





























                0














                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






                share|improve this answer





























                  0














                  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;





                  share|improve this answer























                    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
                    });


                    }
                    });














                    draft saved

                    draft discarded


















                    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









                    65














                    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.






                    share|improve this answer





















                    • +1 See also stackoverflow.com/questions/2211927/…
                      – trashgod
                      Mar 5 '10 at 4:27
















                    65














                    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.






                    share|improve this answer





















                    • +1 See also stackoverflow.com/questions/2211927/…
                      – trashgod
                      Mar 5 '10 at 4:27














                    65












                    65








                    65






                    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.






                    share|improve this answer












                    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.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    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


















                    • +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













                    27














                    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:




                    1. 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


                    2. 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;


                    3. 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 ints at all.






                    share|improve this answer



















                    • 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 be ret |= (int)bytes[i + offset] & 0xFF; - otherwise the offset param is ignored completely.
                      – Ying
                      Feb 9 '17 at 0:23
















                    27














                    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:




                    1. 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


                    2. 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;


                    3. 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 ints at all.






                    share|improve this answer



















                    • 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 be ret |= (int)bytes[i + offset] & 0xFF; - otherwise the offset param is ignored completely.
                      – Ying
                      Feb 9 '17 at 0:23














                    27












                    27








                    27






                    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:




                    1. 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


                    2. 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;


                    3. 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 ints at all.






                    share|improve this answer














                    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:




                    1. 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


                    2. 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;


                    3. 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 ints at all.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    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 be ret |= (int)bytes[i + offset] & 0xFF; - otherwise the offset param is ignored completely.
                      – Ying
                      Feb 9 '17 at 0:23














                    • 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 be ret |= (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











                    26














                    If you have them already in a byte array, you can use:



                    int result = ByteBuffer.wrap(bytes).getInt();


                    source: here






                    share|improve this answer




























                      26














                      If you have them already in a byte array, you can use:



                      int result = ByteBuffer.wrap(bytes).getInt();


                      source: here






                      share|improve this answer


























                        26












                        26








                        26






                        If you have them already in a byte array, you can use:



                        int result = ByteBuffer.wrap(bytes).getInt();


                        source: here






                        share|improve this answer














                        If you have them already in a byte array, you can use:



                        int result = ByteBuffer.wrap(bytes).getInt();


                        source: here







                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited May 23 '17 at 12:18









                        Community

                        11




                        11










                        answered May 15 '10 at 14:08









                        iTEggiTEgg

                        3,4341864103




                        3,4341864103























                            14














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





                            share|improve this answer

















                            • 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


















                            14














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





                            share|improve this answer

















                            • 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
















                            14












                            14








                            14






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





                            share|improve this answer












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






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            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
















                            • 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













                            5














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





                            share|improve this answer



















                            • 1




                              assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
                              – stmax
                              Mar 4 '10 at 22:54
















                            5














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





                            share|improve this answer



















                            • 1




                              assuming that his binary file contains big endian signed ints. otherwise it'll fail. horribly. :)
                              – stmax
                              Mar 4 '10 at 22:54














                            5












                            5








                            5






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





                            share|improve this answer














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






                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            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














                            • 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











                            4














                            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.






                            share|improve this answer

















                            • 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 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










                            • 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
















                            4














                            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.






                            share|improve this answer

















                            • 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 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










                            • 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














                            4












                            4








                            4






                            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.






                            share|improve this answer












                            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.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            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 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










                            • 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




                              +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 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










                            • 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











                            1














                            for (int i = 0; i < buffer.length; i++)
                            {
                            a = (a << 8) | buffer[i];
                            if (i % 3 == 0)
                            {
                            //a is ready
                            a = 0;
                            }
                            }





                            share|improve this answer


























                              1














                              for (int i = 0; i < buffer.length; i++)
                              {
                              a = (a << 8) | buffer[i];
                              if (i % 3 == 0)
                              {
                              //a is ready
                              a = 0;
                              }
                              }





                              share|improve this answer
























                                1












                                1








                                1






                                for (int i = 0; i < buffer.length; i++)
                                {
                                a = (a << 8) | buffer[i];
                                if (i % 3 == 0)
                                {
                                //a is ready
                                a = 0;
                                }
                                }





                                share|improve this answer












                                for (int i = 0; i < buffer.length; i++)
                                {
                                a = (a << 8) | buffer[i];
                                if (i % 3 == 0)
                                {
                                //a is ready
                                a = 0;
                                }
                                }






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 4 '10 at 22:49









                                AndreyAndrey

                                51.3k993144




                                51.3k993144























                                    1














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





                                    share|improve this answer


























                                      1














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





                                      share|improve this answer
























                                        1












                                        1








                                        1






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





                                        share|improve this answer












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






                                        share|improve this answer












                                        share|improve this answer



                                        share|improve this answer










                                        answered Jul 31 '13 at 20:36









                                        Jamel TomsJamel Toms

                                        3,14222024




                                        3,14222024























                                            0














                                            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






                                            share|improve this answer


























                                              0














                                              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






                                              share|improve this answer
























                                                0












                                                0








                                                0






                                                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






                                                share|improve this answer












                                                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







                                                share|improve this answer












                                                share|improve this answer



                                                share|improve this answer










                                                answered Apr 7 '18 at 5:52









                                                MounirMounir

                                                1




                                                1























                                                    0














                                                    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;





                                                    share|improve this answer




























                                                      0














                                                      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;





                                                      share|improve this answer


























                                                        0












                                                        0








                                                        0






                                                        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;





                                                        share|improve this answer














                                                        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;






                                                        share|improve this answer














                                                        share|improve this answer



                                                        share|improve this answer








                                                        edited Nov 23 '18 at 18:46

























                                                        answered Nov 23 '18 at 18:39









                                                        NathanNathan

                                                        3,41052751




                                                        3,41052751






























                                                            draft saved

                                                            draft discarded




















































                                                            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.




                                                            draft saved


                                                            draft discarded














                                                            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





















































                                                            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







                                                            Popular posts from this blog

                                                            A CLEAN and SIMPLE way to add appendices to Table of Contents and bookmarks

                                                            Calculate evaluation metrics using cross_val_predict sklearn

                                                            Insert data from modal to MySQL (multiple modal on website)