Archived

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

Galileo430

Java and Byte Arrays

Recommended Posts

I start out this morning with a blank screen. (Thx GD.Net ) Learn some java and now I''m sitting staring at what I hope will be a networked version of PONG. Only one problem. I can''t seem to get the ball data and the paddle data into a byte[] to send. In c++ I would use memcpy to copy the data from a struct or a nasty varible that wouldn''t type cast into a the char array. I don''t know if there is such a function in Java. However if anyone knows a smart way to trasfer both text and numbers in and out of byte arrays into CStrings and ints. I would be very grateful.

Share this post


Link to post
Share on other sites
Strings have a nifty function called getBytes() that returns a byte array, and a constructor that takes a byte array.
Basic types can be masked and shifted into bytes.

You might also want to look at java.io.DataInputStream and java.io.DataOutputStream. Does all that nasty stuff for you. Only warning is that Strings are sent in Unicode when using DataOutputStream.writeUTF(), so it takes 16 bits per character (as well as an extra int for the length of the string).

If you''re going between a Java program and a native (C/C++) program, don''t forget to handle byte-order.

"So crucify the ego, before it''s far too late. To leave behind this place so negative and blind and cynical, and you will come to find that we are all one mind. Capable of all that''s imagined and all conceivable."
- Tool
------------------------------

Share this post


Link to post
Share on other sites
Galileo,

I''m not sure why you need data into a byte[], I guess to send data over the network using one an java.io.InputStream obtained from a java.net.Socket?

If this is the case you might find the two object stream classes useful. ( java.io.ObjectInputStream & ObjectOutputStream ) these classes can be used to send objects into and out of other input and output streams.

So the psydo code something like

// Create and open socket.
Socket myEnd = ..some connection stuff..

// Create raw output stream
OutputStream rawOut = myEnd.getOutputStream();

// Create an object output stream over the raw output stream
ObjectOutputStream objectOut = new ObjectOutputStream (rawOut);

// Send some object(s)
objectOut.writeObject ( myPaddle );

Where myPaddle is an instance of your paddle class containing any data you want to send ( Or write a simple message class - like a ''C'' style class, holding all the data as public members )

// At the far end paddle data could be extracted as an object
// and cast to the expected type

otherPaddle = (CPaddle) objectIn.readObject();

Anyway to send objects through a ObjectInputStream/ ObjectOutputStream the objects need to implement java.io.Serializable interface ( an empty interface ).

Tom.

Share this post


Link to post
Share on other sites