Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
Solved

Byte Array to Integer

Posted on 1998-04-12
Medium Priority
542 Views
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
Question by:iwt
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 1

Expert Comment

ID: 1234052
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

ID: 1234053
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

anguslai earned 280 total points
ID: 1234054
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

Question has a verified solution.

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

Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Introduction This article is the last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Suggested Courses
Course of the Month6 days, 2 hours left to enroll