티스토리 뷰

반응형

[c#/wpf/winform/unity] Byte to String  / String to Byte 로 변환 컨버팅

#static으로 손쉽게 사용이 가능하다

 

 public static class ByteConverter
    {
        public static object ByteToObject(byte[] buffer)
        {
            try
            {
                using (MemoryStream stream = new MemoryStream(buffer))
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    stream.Position = 0;
                    return binaryFormatter.Deserialize(stream);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
            return null;
        }

        public static byte[] ObjectToByte(object obj)
        {
            try
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    BinaryFormatter binaryFormatter = new BinaryFormatter();
                    binaryFormatter.Serialize(stream, obj);
                    return stream.ToArray();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.ToString());
            }
            return null;
        }

        // 바이트 배열을 String으로 변환 
        public static string ByteToString(byte[] buffer) {
            string str = Encoding.Default.GetString(buffer);
            return str;
        }
        // String을 바이트 배열로 변환 
        public static byte[] StringToByte(string str) {
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            return buffer;
        }

    }

 

#ByteToString #StringToByte #c# #wpf #winform #unity

반응형
댓글
반응형