converting int and short to byte array and vice versa

C

carmen

Hi,

Could anyone suggest a way to convert a short to a 2 byte array and a
int to a 4 byte array and vice versa? Is there any way to do it using
utility classes provided by java?
I have just begun to code in java :(,

regards,
Carmen
 
F

foo

// For int. for short is similar

/**
* Returns rightmost byte as the 0th element of the array
*/
bytesValue(int myInt) {
byte[] bytes = new byte[4];
hexBase = 0xff; // A byte of all ones
bytes[0] = hexBase & myInt;
bytes[1] = ((hexBase << 8) & myInt) >> 8;
bytes[2] = ((hexBase << 16) & myInt) >> 16;
bytes[3] = ((hexBase << 24) & myInt) >> 24;
return byte;
}

intValue(byte[] bytes) {
int myInt = bytes[3];
myInt = (myInt << 8) | bytes[2];
myInt = (myInt << 8) | bytes[1];
myInt = (myInt << 8) | bytes[0];
return myInt;
}
 
S

Steve Horsley

carmen said:
Hi,

Could anyone suggest a way to convert a short to a 2 byte array and a
int to a 4 byte array and vice versa? Is there any way to do it using
utility classes provided by java?
I have just begun to code in java :(,

regards,
Carmen

The inbuilt utilities are probably to wrap a DataOutputStream
round a ByteArrayOutputStream, and DataInputStream round a
ByteArrayInputStream, but foo's bit-shifting ways are probably
quicker and easier.

Steve
 
Joined
Jan 13, 2009
Messages
1
Reaction score
0
Hi,
I was looking for the answer to the same question (with shorts ) and got a hint from foo's answer, but didn't get it to work. So I decided to learn the basics about bits to solve it. I had a lot of help from the Campfire story "Cat and Mouse Games with Bits" at the site "JavaRanch".
Then I found my own solution of the problem, and then i found that it was almost identical with foo's. :)
I think that the reason why foo's code didn't work for me was (not only that 8 followed by ) looks like a 8) ) that when you add the bytes bitwise java treats them like integers and fills remaining bytes with ones or zeros depending on sign. In foo's code it can probably be solved by adding the "hexBase" to the second part. Turning this:
foo said:
...
myInt = (myInt << 8 ) | bytes[2];
...
to something similar to this:
...
myInt = (myInt << 8 ) | (bytes[2] & hexBase ) ;
...
At least my code is working now.
Thank you all!
Erik
 
Joined
Jan 12, 2010
Messages
1
Reaction score
0
I have an array of byte:
byte number = new byte[2];

all numerical valure int array "number" are expressend as multi-byte integer.
I would convert the numer into array "number" as int (integer).

how made?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,012
Latest member
RoxanneDzm

Latest Threads

Top