converting a int array to a byte array

C

cryptogirl

Hello,

I need to convert an int array to a byte array. The int array is
divided into elements of 8 bits long. Any code would help.

Thank you
 
V

VisionSet

cryptogirl said:
Hello,

I need to convert an int array to a byte array. The int array is
divided into elements of 8 bits long. Any code would help.

Thank you

List<Byte> bytes = new ArrayList<Byte>();
int[] array = ...

for (int i = 0; i < array.length; i++) {

bytes.add((byte)(array >> 24));
bytes.add((byte)(array >> 16));
bytes.add((byte)(array >> 8));
bytes.add((byte)(array >> 0));

}

byte[] barry = bytes.asArray(new byte[bytes.size()]);

there's probably a quicker way
 
U

uhon

Hi here the method I use to convert an int to ByteArray. I assume that
it suit with your needs.

Attention int is 4 Bytes long, if you want to produce longer byteArrays
with leading zeros, ajust the length variable.

private byte[] makeByteArray(int value, int length) {
byte[] b = new byte[length];

for (int i = 0; i < length; i++) {
int offset = (b.length - 1 - i) * 8;
b = (byte) ((value >>> offset) & 0xFF);
}
if(b.length > 4) {
for(int i = 0; i < b.length - 4; i++) {
b = 0;
}
}
return b;
}

cryptogirl said:
Hello,

I need to convert an int array to a byte array. The int array is
divided into elements of 8 bits long. Any code would help.

Thank you

List<Byte> bytes = new ArrayList<Byte>();
int[] array = ...

for (int i = 0; i < array.length; i++) {

bytes.add((byte)(array >> 24));
bytes.add((byte)(array >> 16));
bytes.add((byte)(array >> 8));
bytes.add((byte)(array >> 0));

}

byte[] barry = bytes.asArray(new byte[bytes.size()]);

there's probably a quicker way
 
C

Chris Uppal

VisionSet said:
List<Byte> bytes = new ArrayList<Byte>();

Probably not a good idea to use an ArrayList<Byte> -- very wasteful of time and
space.

(Unless you know that you aren't doing it often, or with many bytes-worth of
input.)

-- chris
 
C

cryptogirl

Okay my array length will be any were between 1-1500 bytes. so where
ever there is a 4 i change it to 1500?
 

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

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top