C structure available in Java

I have a C structure that is sent over some intermediate networks and receives Java code through a serial link. Java code gives me an array of bytes, which I now want to repackage as the source structure. Now, if the receipt code was in C, it was simple. Is there an easy way to repack byte [] in java for structure C. I have minimal experience with java, but this does not seem to be a common problem or not resolved in any frequently asked questions that I can find.

FYI structure C

struct data {
     uint8_t        moteID;
    uint8_t     status; //block or not
    uint16_t   tc_1;
    uint16_t   tc_2;
    uint16_t   panelTemp;  //board temp
    uint16_t   epoch#;
    uint16_t   count;    //pkt seq since the start of epoch
    uint16_t   TEG_v;   
    int16_t   TEG_c;    
 }data;
+3
source share
4 answers

. :

  • .
  • , ( ).

, Java , Java ( JVM ).

- java.nio.ByteBuffer, ; , / java.nio. , (, ..), , , , .

:

public class Data {

    private byte moteId;
    private byte status;
    private short tc_1;
    private short tc_2;
    //...etc...
    private int tc_2_as_int;

    private Data() {
        // empty
    }

    public static Data createFromBytes(byte[] bytes) throws IOException {
        final Data data = new Data();
        final ByteBuffer buf = ByteBuffer.wrap(bytes);

        // If needed...
        //buf.order(ByteOrder.LITTLE_ENDIAN);

        data.moteId = buf.get();
        data.status = buf.get();
        data.tc_1 = buf.getShort();
        data.tc_2 = buf.getShort();
        // ...extract other fields here

        // Example to convert unsigned short to a positive int
        data.tc_2_as_int = buf.getShort() & 0xffff;

        return data;        
    }

}

, , Data.createFromBytes(byteArray).

, Java , . , , . , , . (byte → short, short → int; int → long).

: , , short (16- ) int (32- ) tc_2_as_int.

, , , java.nio.ByteBuffer buf.order(ByteOrder.LITTLE_ENDIAN);, .

+7

C C.

, , /, , , . , , , , , , . !

, , . . C/++ -

32/64- , "int" "long", ... : -)

, Java ... . , , , ( , ), .

. ,

class Data
{
    public int        moteID;
    public int        status; //block or not
    public int        tc_1;
    public int        tc_2;
}

, , -

Data convertBytesToData(byte[] dataToConvert)
{
    Data d = Data();
    d.moteId = (int)dataToConvert[0];
    d.status = (int)dataToConvert[1];
    d.tc_1 = ((int)dataToConvert[2] << 8) + dataTocConvert[3];  // unpacking 16-bits
    d.tc_2 = ((int)dataToConvert[4] << 8) + dataTocConvert[5];  // unpacking 16-bits
}

16- , C, , . Java , , , [] , . , # .

, , JSON !

+2

, , , , , C Java. JSON .

+1

, , :

  • C uint16_t ( int16_t) . , . .

  • C - . , (), .

, , , struct... , , / C C.

, Java , "endian-ness". DataInputStream DataOutputStream , / . , Java, .

: ( @Kevin Brock) java.nio.ByteBuffer .

0

Source: https://habr.com/ru/post/1730310/


All Articles