Question

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...

Was it helpful?

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?

OTHER TIPS

Please try to avoid the \x escape sequence. It's difficult to read because where it stops depends on the data. For instance, how much difference is there at a glance between these two strings?

"\x9Good compiler"
"\x9Bad compiler"

In the former, the "\x9" is tab - the escape sequence stops there because 'G' is not a valid hex character. In the second string, "\x9Bad" is all an escape sequence, leaving you with some random Unicode character and " compiler".

I suggest you use the \u escape sequence instead:

"\u0009Good compiler"
"\u0009Bad compiler"

(Of course for tab you'd use \t but I hope you see what I mean...)

This is somewhat aside from the original question of course, but that's been answered already :)

There's an '\u' escape code for hexadecimal 16 bits unicode character codes.

Console.WriteLine( "Look, I'm so happy : \u263A" );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top