Solved

How to convert a byte[] to an integer

Posted on 2002-03-28
6
253 Views
Last Modified: 2012-05-04
I have a byte[] with four bytes!
for example:
byte [] k={23,39,23,40}
how to convert k[] to an integer?
0
Comment
Question by:liluqun
  • 3
  • 2
6 Comments
 
LVL 16

Expert Comment

by:Peter Kwan
ID: 6904262
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];
     }

0
 
LVL 9

Expert Comment

by:Ovi
ID: 6904583
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;
}
0
 
LVL 16

Expert Comment

by:Peter Kwan
ID: 6904597
Ovi, your method does not work.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 9

Expert Comment

by:Ovi
ID: 6904607
Sorry about that, I've tested myself after I posted. Please ignore the comment.
0
 

Author Comment

by:liluqun
ID: 6904635
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
0
 
LVL 16

Accepted Solution

by:
Peter Kwan earned 20 total points
ID: 6904659
This is because "byte" is 8-bit 2's complement.

Here is a working version:

 if (w[0] < 0)
   y += 256;       // 2^8 = 256
 y=w[0];
 for (int i=1; i<4; i++) {
    y = y << 8;
    if (w[i] < 0)
      y+=256;
    y += w[i];
 }
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question