Converts a byte array to a ASCII string - CSharp System

CSharp examples for System:Byte Array

Description

Converts a byte array to a ASCII string

Demo Code


using System.Text;
using System.Linq;
using System;//from  ww  w. ja v a2 s  . c  o m

public class Main{
        /// <summary>
        /// Converts a byte array to a ASCII string
        /// </summary>
        /// <param name="value">
        /// Byte array to convert to a string
        /// </param>
        /// <returns>
        /// The converted string, or an empty string when no null-terminator was
        /// found in the byte array
        /// </returns>
        /// <remarks>
        /// </remarks>
        public static string ConvertBytesToASCIIString(byte[] value)
        {
            if (value == null)
                throw new ArgumentNullException("value");

            string result = "";

            if (value.Length != 0)
            {
                // Find 0-terminator
                int nullTerminatorPosition = 0;
                for (int i = 0; i < value.Length; i++)
                {
                    if (value[i] == 0x0)
                    {
                        nullTerminatorPosition = i;
                        break;
                    }
                }

                byte[] realData = new byte[value.Length - (value.Length - nullTerminatorPosition)];
                for (int i = 0; i < realData.Length; i++)
                {
                    realData[i] = value[i];
                }

                result = Encoding.ASCII.GetString(realData);
            }

            return result;
        }
}

Related Tutorials