Solved

convert int(short or long) to byte array

Posted on 2002-03-04
8
78,985 Views
Last Modified: 2011-08-18
I intend to convert a integer (or short or long) that is greater than a byte can hold (eg, 1111) to a byte array, since casting is simply cannot be used here, any other way can do it without lose precise? I have tried to use Integer wrapper class and use its toBinaryString() to convert the int to a string representation, eg 5->"101", then I really cannot find a way of converting "101" to a byte array with correct binary representation. Please help
0
Comment
Question by:gordon_guan
8 Comments
 
LVL 9

Expert Comment

by:Venci75
ID: 6839117
try this:
"101".getBytes();
0
 
LVL 9

Expert Comment

by:Venci75
ID: 6839172
String str = Integer.toBinaryString(12345);
byte[] byte_array = str.getBytes();
0
 
LVL 7

Accepted Solution

by:
Igor Bazarny earned 20 total points
ID: 6839424
Hi,

Try this:

int value = 0xcafebabe;
byte[] bytes = new byte[4];

for( int i=0; i<bytes.length; ++i ){
    int offset = (bytes.length-i-1)*8;
    bytes[i] = (value & (0xff << offset)) >>> offset;
}

for( int i=0; i<bytes.length; ++i ){
    System.out.print(Integer.toHexString(bytes[i])+" ");
}
System.out.println();

Regards,
Igor Bazarny,
Brainbench MVP for Java 1
www.brainbench.com
0
Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

 

Author Comment

by:gordon_guan
ID: 6841193
hello vinci, I would say your answer is not the thing that I want and in my case, it is wrong. I would rather prefer bazany's answer since what he/she does is more or less the same as what I did. So please change the answer back. Thanks.
0
 

Author Comment

by:gordon_guan
ID: 6841194
hello vinci, I would say your answer is not the thing that I want and in my case, it is wrong. I would rather prefer bazany's answer since what he/she does is more or less the same as what I did. So please change the answer back. Thanks.
0
 
LVL 4

Expert Comment

by:m_onkey_boy
ID: 6842116
Here's another way:

private byte[] getBytes(int n) {
     BigInteger big = new BigInteger(Integer.toString(n));
     return big.toByteArray();
}
0
 
LVL 2

Expert Comment

by:UniDyne
ID: 9337726
Assuming v is the value of the integer you are trying to convert to bytes, try this:


byte b[] = new byte[4];
int i, shift;
            
for(i = 0, shift = 24; i < 4; i++, shift -= 8)
b[i] = (byte)(0xFF & (v >> shift));
0
 

Expert Comment

by:PingBannon
ID: 13517210
This is a more readable (and faster) solution than unidyne's.

I've also included the code to recreate the int from the byte array.  This is a fragment of a class I wrote called ByteArrayUtils; if anyone can give me a faster solution, I'd be very grateful!

Enjoy!

public static final int   NUMBER_OF_BITS_IN_A_BYTE = 8;
public static final short MASK_TO_BYTE             = 0xFF;
public static final int   SIZE_OF_AN_INT_IN_BYTES  = 4;


public static void writeInt( byte[] p_dest,  // not allocated and returned so array can be reused
                             int    p_toWrite )
{
    assert( p_dest.length >= SIZE_OF_AN_INT_IN_BYTES )
          : "Programming error: p_dest is too short to hold an int";
   
    // unrolled loop of 4 iterations
    p_dest[0] = p_toWrite & MASK_TO_BYTE );
    p_toWrite >>= NUMBER_OF_BITS_IN_A_BYTE;

    p_dest[1] = p_toWrite & MASK_TO_BYTE );
    p_toWrite >>= NUMBER_OF_BITS_IN_A_BYTE;

    p_dest[2] = p_toWrite & MASK_TO_BYTE );
    p_toWrite >>= NUMBER_OF_BITS_IN_A_BYTE;

    p_dest[3] = p_toWrite & MASK_TO_BYTE );
}

   
public static int readInt( byte[] p_src ) // must be of size 4
{
    assert( p_src.length >= SIZE_OF_AN_INT_IN_BYTES )
          : "Programming error: p_src is too short to hold an int";

    // unrolled loop of 4 iterations
    int result = (   p_src[ 0 ] & MASK_TO_BYTE );
    result    |= ( ( p_src[ 1 ] & MASK_TO_BYTE ) << 8 );
    result    |= ( ( p_src[ 2 ] & MASK_TO_BYTE ) << 16 );
    result    |= ( ( p_src[ 3 ] & MASK_TO_BYTE ) << 24 );

    return result;
}
0

Featured Post

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
oracle 11g 23 73
MySQL  on Tomcat 8 43
Configure a Bean in an XML file 4 31
jsp login check 12 28
This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
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 one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

813 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

11 Experts available now in Live!

Get 1:1 Help Now