Solved

How to convert a byte[] to an integer

Posted on 2002-03-28
6
246 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…

914 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

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now