Search code examples
c#bytebitconverter

Convert eight bytes into a string


i have eight byte variables:

Byte7 = 0 dez, hex: 00
Byte6 = 2 dez, hex: 02
Byte5 = 32 dez, hex: 20
Byte4 = 33 dez, hex: 21
Byte3 = 17 dez, hex: 11
Byte2 = 37 dez, hex: 25
Byte1 = 3 dez, hex: 03
Byte0 = 88 dez, hex: 58

Question: How can i put all these together into only one string that then has the hex-value of each byte? The result string should be like this: 0002202111250358

Thanks


Solution

  • If you want to generalise this to any number of bytes (within reason) you could write a helper method to do this:

    public static string BytesToString(params byte[] bytes)
    {
        return string.Concat(bytes.Select(b => b.ToString("X2")));
    }
    

    Which you can then call with any number of bytes:

    public static void Main()
    {
        byte Byte7 = 0;
        byte Byte6 = 2;
        byte Byte5 = 32;
        byte Byte4 = 33;
        byte Byte3 = 17;
        byte Byte2 = 37;
        byte Byte1 = 3;
        byte Byte0 = 88;
    
        var result = BytesToString(Byte7, Byte6, Byte5, Byte4, Byte3, Byte2, Byte1, Byte0);
        Console.WriteLine(result); // 0002202111250358
    }