Advertisement Jump to content


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


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

This topic is 6855 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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
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
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

  • Advertisement

Important Information

By using, you agree to our community Guidelines, Terms of Use, and Privacy Policy. is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!