dcsimg
Login | Register   
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Java Language
Expertise: Beginner
Feb 26, 1998

WEBINAR:

On-Demand

Application Security Testing: An Integral Part of DevOps


byte array to int conversion

Question:
I have just read a packet of data into a byte array from a socket. At offsets 5-8, 9-12, and 13-16 are binary integers. How can I get them into Java int variables?

Answer:
The recommended way of doing this is to use java.io.ObjectInputStream and its readInt() method. However, there are cases where you will want to deal with bytes directly, such as when you are converting little-endian integers to big-endian integers. The easiest way to address how to do this is simply to give an example. The following program takes four bytes in big-endian order and turns them into a Java integer:

public final class bytesToInt {

  public static final void main(String[] args) {
    byte[] bytes;
    int result, bitmask;

    bytes = new byte[4];
    bytes[0] = 1; // 00000001
    bytes[1] = 2; // 00000010
    bytes[2] = 3; // 00000011
    bytes[3] = 4; // 00000100

    result = 0;
    result |= ((0xff & bytes[0]) << 24);
    result |= ((0xff & bytes[1]) << 16);
    result |= ((0xff & bytes[2]) << 8);
    result |= (0xff & bytes[3]);

    System.out.println("int : " + result);
    System.out.print("bits: ");

    // Print the individual bits to show they were set correctly
    bitmask = 0x80000000;
    for(int i=0; i < 32; i++) {
      if((result & bitmask) == 0)
	System.out.print('0');
      else
	System.out.print('1');
      bitmask >>>= 1;
    }
    System.out.println();
  }

}
DevX Pro
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date