Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c#: string format

Tags:

string

c#

I came across a code. Can anybody shed a bit of light on it. Plz be kind if anybody finds it a bit basic.

string str= String.Format("{0,2:X2}", (int)value);

Thankyou for your time.

like image 545
saam Avatar asked Mar 28 '13 13:03

saam


2 Answers

X format returns Hexadecimal representation of your value.

for example String.Format("{0:X}", 10) will return "A", not "10"

X2 will add zeros to the left, if your hexadecimal representation is less than two symbols

for example String.Format("{0:X2}", 10) will return "0A", not "A"

0,2 will add spaces to the left, if the resulting number of symbols is less than 2.

for example String.Format("{0,3:X2}", 10) will return " 0A", but not "0A"

So as result this format {0,2:X2} will return your value in Hexadecimal notation appended by one zero from the left if it is only one symbol and then appended by space from the left if is it one symbol. After reading this several times, you can see, that ,2 is redundant and this format can be simplified to {0:X2} without changing the behavior.

Some notes:

: separates indexing number and specific format applied to that object. For example this code

String.Format("{0:X} {1:N} {0:N}", 10, 20)

shows, that I want to format 10 (index 0) in hexadecimal then show 20 (index 1) in numerical way, and then also format 10 (index 0) in numeric way.

0,2 from the left part of semi-column indicated index position 0 and format ,2 applied to the resulting string, not to a specific object. So this code

String.Format("{0,1} {1,2} {0,4}", 10, 20)

will print first number with at least one symbol, second with at least two symbols and then again first number with at least four symbols occupied. If the number of symbols in resulting string will be less - they will be populated by spaces.

like image 177
Ilya Ivanov Avatar answered Oct 01 '22 07:10

Ilya Ivanov


{0,2:X2}

It splits into

  1. 0,2 - Format a number 10 into 10
  2. X2 - Formats a number 10 into hexadecimel value 0A.

Update

Code

String.Format("{0,2:X2}", (int)value); // where value = 10

Result: 0A

Live Example: http://ideone.com/NW0U26

Conclusion from me
You can change "{0,2:X2}" to "{0:X2}", live example here.

Reference Links: MSDN

like image 29
Harsh Baid Avatar answered Oct 01 '22 08:10

Harsh Baid