Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Convert byte array to hexadecimal string

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 143
    Comment on it

    To convert a byte array to hexadecimal string we use a following two methods:

     

    Method 1:

    In first method we use a BitConverter.ToString( Byte[] )

    This method convert the define array of bytes to the hexadecimal string format.

     

    Syntax:

    public static string ToString( byte[] byteArray )

    It accept one parameter "byteArray" which contain an array of System.Byte type.

    Its return type is System.String.

    It returns a hexadecimal pairs of string.

    For example:-

    "AF-20-BA-11".

    It throws an exception "ArgumentNullException" only if the value is null.

     

    A sample C# code to convert byte array to hexadecimal string.

    using System;
    
    class Program
    {
       public static void ArrayByte(byte[] b)
       {
          Console.WriteLine(BitConverter.ToString(b));
          Console.WriteLine();
       }
    
       public static void Main( )
       {
          byte[] a1 = { 1,4,8,0,16,32,64,128,25,197,41,172 };
          ArrayByte(a1);
          Console.ReadKey();
       }
    }

    Output

    01-04-08-00-10-20-40-80-19-C5-29-AC

     

    Method 2:

    In Second method we write some logic to convert the define array of bytes to hexadecimal string format.

    using System;
    
    class SampleProgramBytesToString
    {
      static string ByteToHexString(byte[] b)
       {
          char[] ch = new char[b.Length * 2];
          int a;
          for (int i = 0; i < b.Length; i++) 
          {
            a = b[i] >> 4;
            ch[i * 2] = (char)(55 + a + (((a-10)>>31)&-7));
            a = b[i] & 0xF;
            ch[i * 2 + 1] = (char)(55 + a+ (((a-10)>>31)&-7));
          }
          string str = new string(ch);
          return (str);
       }
      public static void Main( )
        {
          byte[ ] a = { 1,4,8,0,16,32,64,128,25,197,41,172 };
          string str = ByteToHexString(a1);
          Console.WriteLine(str);
          Console.ReadKey();
         }
    }

    Output

    010408001020408019C529AC

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: