Solved

Byte Array to Integer

Posted on 1998-04-12
3
516 Views
Last Modified: 2009-07-29
I have a byte[] array of size 4 which I want to convert into a 4-byte int or Integer. What method should I use to do this?

I have tried:
String key = new String(bArray, 0, 3);
int result = Integer.valueOf(key).intValue();

which does not seem to work.

Any help would be appreciated.
0
Comment
Question by:iwt
3 Comments
 
LVL 1

Expert Comment

by:peter_vc
Comment Utility
I think you can just cast it to an Integer:

String key = new String(bArray,0,3);
int result = int(key);

I don't have my Java stuff installed on this machine so I can't test it.

0
 

Author Comment

by:iwt
Comment Utility
No answer needed; I found a solution using the code from RandomAccessFile.java's WriteInt() and reversing it, which bypasses the need for a String.

For others' use, I've posted it below:

int result = ((bArray[0] << 24) | (bArray[1] << 16) + (bArray[2] << 8) + bArray[3]);

0
 
LVL 2

Accepted Solution

by:
anguslai earned 70 total points
Comment Utility
Convert a byte array of 4 into 32 bits integer :

Assume :
     byte array named byteArray
     byte[0] contained the left most  8 bits (bit 25 to bit 32);
     
then use the following code to convert byteArray to int:
    int A = byteArray[0]<<24 | byteArray[1]<<16 | byteArray[2]<<8 | byteArray[3];

Note: the left most bit in primitive type int is a sign bit. Therefore, don't forget to treat the left most bit in byte[0] as sign bit.
0

Featured Post

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

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

8 Experts available now in Live!

Get 1:1 Help Now