Conversão de array de bytes para string hexadecimais

0
Pessoal, recentemente fiquei com uma dúvida sobre conversão de um simples array de bytes para hexadecimal.
Fica aqui então a dica de uma simples conversão e seu método reverso:
public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}
//ou
public static string ByteArrayToString(byte[] ba)
{
  string hex = BitConverter.ToString(ba);
  return hex.Replace("-","");
}


//Conversão reversa:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

 

Um grande abraço a todos!

 

Compartilhe.

Sobre o autor

Criador do blog Código Simples e com mais 9 anos de experiência em TI, com títulos de MVP Microsoft na área de Visual Studio Development, Neo4j Top 50 Certificate, Scrum Master e MongoDB Evangelist. Atuando em funções analista, desenvolvedor, arquiteto, líder técnico e gestor de equipes. Mais informações em : http://jhonathansoares.com