繁体   English   中英

将字符串 UTF8 编码为字节数组 ASCII,然后编码为 ASCII 字符串,然后在 C# 中将其解码回 UTF8

[英]Encode string UTF8 to byte array ASCII, then to ASCII string, and then decode it back to UTF8 in C#

所以我有来自网站的评论,我想将它作为编码字符串发送到数据库,以防止它破坏数据库。 我是这样做的:

public string ConvertStringToByteArray(string comment)
        {
            Encoding ascii = Encoding.ASCII;
            byte[] asciiBytes = ascii.GetBytes(comment);
            string bitString = BitConverter.ToString(asciiBytes);
            return bitString;
        }

现在我想将它解码回 UTF8 字符串,所以当它显示时,它现在显示为 ASCII 符号。

您可以使用以下方法将上述字符串转换回字符串注释:-

public static string getCommentFromBytes(string bitString)
    {
        string[] arr = bitString.Split('-');
        byte[] barr = new byte[arr.Length];
        for (int i = 0; i < arr.Length; i++)
        {
            barr[i] = Convert.ToByte(arr[i]);
        }
        return System.Text.Encoding.ASCII.GetString(barr);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM