Convert a ASCII byte array to string, also filter out the null characters. - CSharp System

CSharp examples for System:Byte Array

Description

Convert a ASCII byte array to string, also filter out the null characters.

Demo Code


using Microsoft.Win32;
using System.Text;
using System.IO;/*from  w  w w.ja v a  2 s.co  m*/
using System;

public class Main{
        /// <summary>
        /// Convert a ASCII byte array to string, also filter out the null characters.
        /// </summary>
        /// <param name="bytes"></param>
        /// <returns></returns>
        public static string BytesToString(byte[] bytes)
        {
            string retval = "";
            if (bytes == null || bytes.Length < 1) return retval;
            char[] cretval = new char[bytes.Length];
            for (int i=0, j=0; i<bytes.Length; i++)
            {
                if (bytes[i] != '\0')
                {
                    cretval[j++] = (char) bytes[i];
                }
            }
            retval = new string(cretval);
            retval = retval.TrimEnd('\0');
            return retval;
        }
}

Related Tutorials