Is there a canonical way to define a data structure in Java (and by extension Kotlin) which can be serialized into a byte array or sequence of bits in the order the bytes are defined in the structure?
Similar to a Struct in C.
Edit: So, further to this, I would like a simple and expressive way of defining a data structure and then accessing any part of it. So, for instance, in pseudocode:
DataStructure Message {
Bit newFlag;
Bit genderFlag;
Bit sizeFlag;
Bit activeFlag;
Bit[4] operation;
Byte messageSize;
Byte[] message;
}
So then we do:
Message firstMessage = new Message(1, 0, 1, 0, b'0010', 11, "Hello there");
And we can say:
ByteArray serialisedMessage = firstMessage.toBytes();
Which would give us an array which looked like:
[b'10100010', b'00001011', "Hello there" (but in bytes)]
Then we could do:
firstMessage.genderFlag = 1;
..and just rerun .toBytes on the object.
Obviously there are a million ways of doing stuff like this in Java, but nothing syntactically simple, as far as I can see - pretty much anything would involve having to write a custom serialisation (and not object serialisation as per Java) method for each object. Perhaps that's the canonical way to do this, but it would be nice to have it simpler, as per C, Rust, and, erm, COBOL.