I'm new to binary in C# and have a question on the best way to do this. I have an application I'm trying to communicate that has a specific binary message format. It has to begin with a B8
hex code, and end with a BB
hex code, with the binary message in between. What is the best way of being able to take a byte buffer and cast it to the message for easy access to the message properties? I'd imagine a struct, but in all honesty i don't really know.
EDIT:
The reason i don't want it in binary is so that I can easliy use the data in my application. For example, i'd like to convert the binary bits that represent a command type to an enum. Like this (just a representation of what I'd like to do):
struct CommandMessage
{
public CommandType Command { get; set; }
public object Data { get; set; }
}
enum CommandType
{
UserJoined,
MessageReceived
}
I would suggest to use protobuf-net
for DTO
serialization.
So, define some entity e.g Package
(CommandMessage
in your sample) which has
public Command Command;
public byte[] Data;
(serialized with protobuf
)
Based on Command
you will be able to deserialize Data
to concrete DTO
type using protobuf
.
If your message should start with special prefix, you can handle this in Package
as well.
Also, Package
should handle writing/reading itself to/from binary stream or buffers (that's pretty strait forward).
e.g package.WriteTo(buffer)
produces [BB,Command,Data,B8]
. Same for package.ReadFrom()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With