C# | BitConverter.ToString(Byte[]) Method
Last Updated :
01 Feb, 2019
This method is used to convert the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string representation.
Syntax:
public static string ToString (byte[] value);
Here, the value is an array of bytes.
Return Value: This method returns a string of hexadecimal pairs separated by hyphens, where each pair represents the corresponding element in value. For example, “6E-1D-9A-00”.
Exception: This method throws ArgumentNullException if the byte array or you can say value is null.
Below programs illustrate the use of BitConverter.ToString(Byte[]) Method:
Example 1:
using System;
public class GFG {
public static void Main()
{
try {
byte [] array1 = {0, 1, 2, 4, 8, 16,
32, 64, 128, 255};
Console.Write( "Initial Array: " );
PrintIndexAndValues(array1);
string value = BitConverter.ToString(array1);
Console.Write( "string: " );
Console.Write( "{0}" , value);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
public static void PrintIndexAndValues( byte [] myArr)
{
for ( int i = 0; i < myArr.Length; i++) {
Console.Write( "{0} " , myArr[i]);
}
Console.WriteLine();
Console.WriteLine();
}
}
|
Output:
Initial Array: 0 1 2 4 8 16 32 64 128 255
string: 00-01-02-04-08-10-20-40-80-FF
Example 2: For ArgumentNullException
using System;
public class GFG {
public static void Main()
{
try {
byte [] array1 = null ;
string value = BitConverter.ToString(array1);
Console.Write( "string: " );
Console.Write( "{0}" , value);
}
catch (ArgumentNullException e) {
Console.Write( "Exception Thrown: " );
Console.Write( "{0}" , e.GetType(), e.Message);
}
}
}
|
Output:
Exception Thrown: System.ArgumentNullException
Reference:
Share your thoughts in the comments
Please Login to comment...