C#- Convertir matriz de bytes en cadena hexadecimal y viceversa
En este artículo, aprenderemos cómo convertir una matriz de bytes en una cadena hexadecimal y viceversa en C#
Forma 1:
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(); }
Forma 2:
public static string ByteArrayToString(byte[] ba) { string hex = BitConverter.ToString(ba); return hex.Replace("-",""); }
Forma 3:
using System.Runtime.Remoting.Metadata.W3cXsd2001; public static byte[] GetStringToBytes(string value) { SoapHexBinary shb = SoapHexBinary.Parse(value); return shb.Value; }
Convertir cadena hexadecimal en matriz de bytes en C#:
Forma 1:
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; }
Forma 2:
using System.Runtime.Remoting.Metadata.W3cXsd2001; public static string GetBytesToString(byte[] value) { SoapHexBinary shb = new SoapHexBinary(value); return shb.ToString(); }
¡¡Gracias por visitarnos!!