C# | BitConverter.ToString(Byte[]) Method
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:
// C# program to demonstrate // BitConverter.ToString(Byte[]); // Method using System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte [] array1 = {0, 1, 2, 4, 8, 16, 32, 64, 128, 255}; // Display the values of the myArr. Console.Write( "Initial Array: " ); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(array1); // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string Console.Write( "string: " ); Console.Write( "{0}" , value); } catch (ArgumentNullException e) { Console.Write( "Exception Thrown: " ); Console.Write( "{0}" , e.GetType(), e.Message); } } // Defining the method // PrintIndexAndValues 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
// C# program to demonstrate // BitConverter.ToString(Byte[]); // Method using System; public class GFG { // Main Method public static void Main() { try { // Define an array of byte values. byte [] array1 = null ; // Getting hex string of byte values string value = BitConverter.ToString(array1); // Display the string 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:
- https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.tostring?view=netframework-4.7.2#System_BitConverter_ToString_System_Byte___
Contact Us