Solved

How to convert a byte[] to an integer

Posted on 2002-03-28
6
242 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
Comment Utility
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
Comment Utility
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
Comment Utility
Ovi, your method does not work.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 9

Expert Comment

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

Author Comment

by:liluqun
Comment Utility
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
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
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…
Viewers learn about the third conditional statement “else if” and use it in an example program. Then additional information about conditional statements is provided, covering the topic thoroughly. Viewers learn about the third conditional statement …
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

763 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

6 Experts available now in Live!

Get 1:1 Help Now