[165] in java-interest
Re: int -> bytes
daemon@ATHENA.MIT.EDU (Arthur van Hoff)
Wed May 31 19:01:00 1995
Date: Wed, 31 May 1995 15:23:42 -0700
From: Arthur.Vanhoff@Eng.Sun.COM (Arthur van Hoff)
To: java-interest@java.Eng.Sun.COM
Hi Peppar,
> How do you code the following in Java?
>
> ---
> byte b[sizeof(i)];
> int i[1];
>
> memcpy((void *)b, (void *)i,sizeof(i));
> ---
> where byte is the Java-byte type.
>
> I need to change an array of ints into bytes to be able to send it over the
> network and on the receiving side change it back into ints. I've tried to use
> arraycopy+casting whitout success.
You can't do it that way. The internal representation of integer arrays
is platform specific so turning it into a byte array does not work.
What you need to do is use a DataOutputStream to write the individual
values to a stream in a byte order independent way. For example:
void writeIntArray(DataOuputStream out, int data[]) {
out.writeInt(data.length);
for (int i = 0 ; i < data.length ; i++) {
out.writeInt(data[i]);
}
}
On the other side you can use a DataInputStream to read the data
from the stream.
Have fun,
Arthur van Hoff (avh@eng.sun.com)
http://java.sun.com/people/avh/
Sun Microsystems Inc, M/S UPAL02-301,
100 Hamilton Avenue, Palo Alto CA 94301, USA
Tel: +1 415 473 7242, Fax: +1 415 473 7104
-
Note to Sun employees: this is an EXTERNAL mailing list!
Info: send 'help' to java-interest-request@java.sun.com