> 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[i] >> 24));
bytes.add((byte)(array[i] >> 16));
bytes.add((byte)(array[i] >> 8));
bytes.add((byte)(array[i] >> 0));
}
byte[] barry = bytes.asArray(new byte[bytes.size()]);
there's probably a quicker way
--
Mike W
uhon - 24 Feb 2006 19:20 GMT
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[i] = (byte) ((value >>> offset) & 0xFF);
}
if(b.length > 4) {
for(int i = 0; i < b.length - 4; i++) {
b[i] = 0;
}
}
return b;
}
VisionSet schrieb:
> > Hello,
> >
[quoted text clipped - 21 lines]
> --
> Mike W
cryptogirl - 25 Feb 2006 15:38 GMT
Okay my array length will be any were between 1-1500 bytes. so where
ever there is a 4 i change it to 1500?
Chris Uppal - 24 Feb 2006 20:05 GMT
> 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
>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.
e
you do it element by element to a new array the same size. So your
problem reduces to converting an int to a byte. See
http://mindprod.com/applets/converter.html

Signature
Canadian Mind Products, Roedy Green.
http://mindprod.com Java custom programming, consulting and coaching.