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
ted_driverAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
CEHJConnect With a Mentor Commented:
Correction:

>>x = (char)in.readByte();

should be

         x = (char)(in.readByte() & 0xFF);

or you could just store that in an int

         x = (in.readByte() & 0xFF); // (where 'x' is an int)



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

bb.getChar() ;
bb.getDouble() ;
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
TimYatesCommented:
Watch out though, "unsigned char" and "char" are not the same type...

"unsigned char" is a single byte, wheras char is 2 bytes
0
 
TimYatesCommented:
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)
0
 
CEHJCommented:
>>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();
      }
}
0
 
objectsCommented:
You can use DataInputStream to read that, it contains methods to read the various primitives.
0
 
CEHJCommented:
8-)
0
All Courses

From novice to tech pro — start learning today.