Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String format and hex chars

Tags:

string

c#

hex

can someone explain why this doesnt work:

string f = string.Format("\\x{0:00}{{0}}", 5);
string o = string.Format(f, "INSERT TEXT");
System.Diagnostics.Debug.WriteLine(f + " : " + o);

Output is:

\x05{0} : \x05INSERT TEXT

why does the \x05 not get replaced?

like image 641
user380689 Avatar asked Nov 04 '10 05:11

user380689


People also ask

What is hex string format?

The format for coding a hexadecimal string mask is: X'yy...yy' The value yy represents any pair of hexadecimal digits that constitute a byte (8 bits). Each bit must be 1 (test bit) or 0 (ignore bit).

What string format means?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string. Syntax: There is two types of string format() method.

Why do we use format string?

Format provides give you great flexibility over the output of the string in a way that is easier to read, write and maintain than just using plain old concatenation. Additionally, it's easier to get culture concerns right with String.

What is format string in C#?

In C#, Format() is a string method. This method is used to replace one or more format items in the specified string with the string representation of a specified object.In other words, this method is used to insert the value of the variable or an object or expression into another string.


2 Answers

The format for the argument should be set in the format specifier, otherwise you're just inserting a literal "\x". Like this:

// "5" as a lowercase 2-digit hex
string f = string.Format("{0:x2}{{0}}", 5);

Don't confuse how you represent a hex literal in source code with what you would print in a formatted string, they are different things.

like image 113
Jeff Mercado Avatar answered Sep 22 '22 06:09

Jeff Mercado


To put a literal char in a string, just make sure that the compiler knows it's a char.

string f = string.Format("{0}", (char)5);
string g = string.Format("{0}", Convert.ToChar(5));
string h = string.Format("{0}", char.ConvertFromUtf32(5));

or you can start out with a real char:

string i = string.Format("{0}", '\x05');
string j = string.Format("{0}", '\u0005');
string k = string.Format("{0}", '\U00000005');

Take your pick.

like image 45
Mr Lister Avatar answered Sep 20 '22 06:09

Mr Lister