Link to home
Start Free TrialLog in
Avatar of liluqun
liluqun

asked on

How to convert a byte[] to an integer

I have a byte[] with four bytes!
for example:
byte [] k={23,39,23,40}
how to convert k[] to an integer?
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

For LittleEndian:

    byte[] k={23,39,23,40};
     int y=0;

     y=k[0];
     for (int i=1; i<4; i++) {
        y = y << 8;
        y += k[i];
     }

For BigEndian:
    byte[] k={23,39,23,40};
     int y=0;

     y=k[3];
     for (int i=2; i>=0; i--) {
        y = y << 8;
        y += k[i];
     }

Avatar of Ovi
Ovi

Or, not worying about manual conversion, like

byte[] byteArray = {1, 2, 3, 4, 4, 5, 6};
int value = -1; // -1 considered as invalid value for this operation.
try {
  value = Integer.parseInt(new String(byteArray));
} catch(Exception e) {
  value = -1;
}
Ovi, your method does not work.
Sorry about that, I've tested myself after I posted. Please ignore the comment.
Avatar of liluqun

ASKER

Now try this code:
===========================================
import java.io.*;

public class Test {

  public Test() {
  }
  public static void main(String[] args) {
    Test test1 = new Test();
    try {
      RandomAccessFile rf=new RandomAccessFile("d:\\ok.txt","rw");
      rf.writeInt(777678);        
      rf.close();
    }
    catch (Exception ex) {
       System.out.print(ex);
    }

  }
}
===============================================
After run the above code , we can get a 4-bytes file!
Now we use bytes arrarys to restore the integer777678,
I know use rf.readInt() can restore the integer 777687 at easy,this time ,suppose I can get a byte arrary from the 4-bytes file ok.txt
Now retore it with the following code:
===============================================
import java.io.*;

public class Test {

  public Test() {
  }
  public static void main(String[] args) {
    Test test1 = new Test();
    try {
      RandomAccessFile rf=new RandomAccessFile("d:\\ok.txt","rw");
     // rf.writeByte();
     //rf.writeInt(777678);
      byte [] w=new byte[4];
      rf.read(w);
    int y=0;

    y=w[0];
    for (int i=1; i<4; i++) {
       y = y << 8;
       y += w[i];
    }

System.out.print(y);
      rf.close();
    }
    catch (Exception ex) {
       System.out.print(ex);
    }

  }
}
============================
we can only get: an integer:711886
       not 777678!!
Why
ASKER CERTIFIED SOLUTION
Avatar of Peter Kwan
Peter Kwan
Flag of Hong Kong image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial