Search code examples
c#network-programmingpacket

Sending HEX values over a packet in C#


I currently have the following:

N.Sockets.UdpClient UD;

UD = new N.Sockets.UdpClient();
UD.Connect("xxx.xxx.xxx.xxx", 5255);
UD.Send( data, data.Length );

How would I send data in hex? I cannot just save it straight into a Byte array.


Solution

  • Hex is just an encoding. It's simply a way of representing a number. The computer works with bits and bytes only -- it has no notion of "hex".

    So any number, whether represented in hex or decimal or binary, can be encoded into a series of bytes:

    var data = new byte[] { 0xFF };
    

    And any hex string can be converted into a number (using, e.g. int.Parse()).

    Things get more interesting when a number exceeds one byte: Then there has to be an agreement of how many bytes will be used to represent the number, and the order they should be in.

    In C#, ints are 4 bytes. Internally, depending on the endianness of the CPU, the most significant byte (highest-valued digits) might be stored first (big-endian) or last (little-endian). Typically, big-endian is used as the standard for communication over the network (remember the sender and receiver might have CPUs with different endianness). But, since you are sending the raw bytes manually, I'll assume you are also reading the raw bytes manually on the other end; if that's the case, you are of course free to use any arbitrary format you like, providing that the client can understand that format unambiguously.

    To encode an int in big-endian order, you can do:

    int num = 0xdeadbeef;
    var unum = (uint)num;    // Convert to uint for correct >> with negative numbers
    var data = new[] {
        (byte)(unum >> 24),
        (byte)(unum >> 16),
        (byte)(unum >> 8),
        (byte)(unum)
    };
    

    Be aware that some packets might never reach the client (this is the main practical difference between TCP and UDP), possibly leading to misinterpretation of the bytes. You should take steps to improve the robustness of your message-sending (e.g. by adding a checksum, and ignoring values whose checksums are invalid or missing).