Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of ToString("X2")? [duplicate]

I'm studying MD5 encryption, and have found this code using Google:

public string CalculateMD5Hash(string input) {      // Primeiro passo, calcular o MD5 hash a partir da string     MD5 md5 = System.Security.Cryptography.MD5.Create();     byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);     byte[] hash = md5.ComputeHash(inputBytes);      // Segundo passo, converter o array de bytes em uma string haxadecimal     StringBuilder sb = new StringBuilder();     for (int i = 0; i < hash.Length; i++)     {         sb.Append(hash[i].ToString("X2"));     }     return sb.ToString(); } 

Why does it use ToString("X2")? How is it different from normal ToString?

like image 302
Lai32290 Avatar asked Dec 23 '13 19:12

Lai32290


1 Answers

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

like image 191
TypeIA Avatar answered Sep 22 '22 13:09

TypeIA