Search code examples
c#stringhex

C# Build hexadecimal notation string


How do I build an escape sequence string in hexadecimal notation.

Example:

string s = "\x1A"; // this will create the hex-value 1A or dec-value 26

I want to be able to build strings with hex-values between 00 to FF like this (in this example 1B)

string s = "\x" + "1B"; // Unrecognized escape sequence

Maybe there's another way of making hexadecimal strings...


Solution

  • You don't store hexadecimal values in strings.

    You can, but it would just be that, a string, and would have to be cast to an integer or a byte to actually read its value.

    You can assign a hexadecimal value as a literal to an int or a byte though:

    Byte value = 0x0FF;
    int value = 0x1B;
    

    So, its easily possible to pass an hexadecimal literal into your string:

    string foo = String.Format("{0} hex test", 0x0BB);
    

    Which would create this string "126 hex test".

    But I don't think that's what you wanted?