Archived

This topic is now archived and is closed to further replies.

roju

[java] Type conversions and arrays (and Datagrams!)

Recommended Posts

roju    122
Ok, here''s the deal.. I have created a class representing the types of events that I would like to send over the network. I am using UDP (in Java, DatagramSocket and DatagramPacket), and I am having trouble actually putting the information into the packet. The problem is that the constructor for DatagramPacket wants a byte array, but all my info is stored in various primitives (and a string). What I want to do is convert them all to byte arrays, then make one large byte array to pass to the constructor. In C, I could just memcpy the info using pointers and offsets and such, but Java has no such ability..

Share this post


Link to post
Share on other sites
SiCrane    11839
Strings you can turn into byte arrays with String.getBytes() method. ex:

String s = "Data";
byte[] data = new byte[s.length()];
s.getBytes(0, s.length(), data, 0);

For receiving non-string data you can use ByteArrayInputStream objects. Chain that to a DataInputStream, and you can use readInt(), readLong(), readChar(), etc. methods with it.

For outputing non-string data you can use ByteArrayOutputStream objects. Chain that to a DataOutputStream, and you can use writeInt(), writeLong(), writeChar(), etc. methods with it.

Share this post


Link to post
Share on other sites
roju    122
That's sounds exactly like what I need, and if Forte didn't take a day to start up, I'd test it out right now.

Ok.. I tried it, and it was exactly what I was looking for. Thanks..

Edited by - roju on 4/11/00 9:38:58 PM

Share this post


Link to post
Share on other sites