How to get byte[] from socket NetworkStream and convert to ASCII char content?

152 Views Asked by At

I get the ASCII table from link reference https://commons.wikimedia.org/wiki/File:ASCII-Table-wide.svg

enter image description here

By the way, i try get content with char ASCII from byte[], which send via NetworkStream socket. I find other link from msdn about this https://learn.microsoft.com/en-us/dotnet/api/system.net.sockets.networkstream.read?view=net-7.0#system-net-sockets-networkstream-read(system-byte()-system-int32-system-int32) . But seem it's something wrong when i try convert byte[] to hexa, and then hexa to ASCII char.

byte[] bytes = new Byte[6144];
int i = myNetworkStream.Read(bytes, 0, bytes.Length);
String data = null;
while (i != 0)
{
    data = Encoding.ASCII.GetString(bytes, 0, i);
    Console.WriteLine("byte to hexa, hexa to ascii char" +  HexToASCII(ByteToHex(bytes[i]))) ;
    Console.WriteLine("Received message, convert string to text : " + StringToHex(data) );  //the result is 00 00 00 0C 00 00 3F 0D 00 00 00 00 05 10 01 00
}

public static String ByteToHex(byte[] data)
{
            string hex = BitConverter.ToString(data);
            return hex.Replace('-', ' ');
}

public static string HexToASCII(String hexString)
{
            try
            {
                string ascii = string.Empty;
                for (int i = 0; i < hexString.Length; i += 2)
                {
                    String hs = string.Empty;
                    hs = hexString.Substring(i, 2);
                    uint decval = System.Convert.ToUInt32(hs, 16);
                    char character = System.Convert.ToChar(decval);
                    ascii += character;
                }
                return ascii;
            }
            catch (Exception ex) 
            { 
                Console.WriteLine(ex.Message); 
            }
            return string.Empty;
}


public static String StringToHex(string data)
{
            StringBuilder sb = new StringBuilder();
            foreach (byte b in data)
            {
                sb.Append(string.Format("{0:X2} ", b));
            }
            return sb.ToString();
}
0

There are 0 best solutions below