Link to home
Start Free TrialLog in
Avatar of ted_driver
ted_driver

asked on

Reading C structures from a socket, converting to Java Data types

I need to connect to a socket and then read in data from that socket that was created using C data structures.  Is there a way to do this without writing byte level parsers?  maybe using a java class with the same data definitions such as

c structure
struct{
unsigned char x;
double y;
....
} myStruct;

java class

class myClass{
char x;
double y;
...
};

will this work?  if so, how do I read the data from the socket into the class data?
Also, I can't find an unsigned keyword in Java, how are unsigned data types created and used in Java?

Thanks for the help
Ted
Avatar of TimYates
TimYates
Flag of United Kingdom of Great Britain and Northern Ireland image

If you use the java.nio classes, wrapped up in a ByteBuffer then you can do funtions like

bb.getChar() ;
bb.getDouble() ;
Watch out though, "unsigned char" and "char" are not the same type...

"unsigned char" is a single byte, wheras char is 2 bytes
what you probably want to do with that, is just read a single byte, and store it in a "short" (so that it is unsigned)
>>Is there a way to do this without writing byte level parsers?  

No

>>maybe using a java class with the same data definitions

You should do that anyway, but it wont affect the parsing

>>Also, I can't find an unsigned keyword in Java, how are unsigned data types created and used in Java?

There is no unsigned keyword and only one unsigned type (char)

The easiest way would be to use a DataInputStream:

MyClass c = new MyClass();
DataInputStream in = new DataInputStream(socket.getInputStream());
c.initFromStream(in);

//====================================
public class MyClass {
      private char x;
      private double y;

      public void setX(char x) {
            this.x = x;
      }

      public char getX() {
            return x;
      }

      public void setY(double y) {
            this.y = y;
      }

      public double getY() {
            return y;
      }

      void readFromStream(DataInputStream in) {
            x = (char)in.readByte();
            y = in.readDouble();
      }
}
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You can use DataInputStream to read that, it contains methods to read the various primitives.
8-)