zoukankan      html  css  js  c++  java
  • 【转】Contrary to the answers here, you DON'T need to worry about encoding!

    For those goals, I honestly do not understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.

    Just do this instead:

    static byte[] GetBytes(string str)
    {
        byte[] bytes = new byte[str.Length * sizeof(char)];
        System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
        return bytes;
    }
    
    static string GetString(byte[] bytes)
    {
        char[] chars = new char[bytes.Length / sizeof(char)];
        System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
        return new string(chars);
    }

    As long as your program (or other programs) don't try to interpret the bytes somehow, which you obviously didn't mention you intend to do, then there is nothing wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.

    Additional benefit to this approach:

    It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!

    It will be encoded and decoded just the same, because you are just looking at the bytes.

    If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters.

  • 相关阅读:
    ODBC是什么
    node学习连接和网站
    MongoDB--连接客户端和服务
    css页面布局--三栏(两边固定中间自适应&两边自适应中间固定)
    MongoDB--搭建mongodb服务器
    MongoDB--编译文件
    MongoDB--运行环境
    Ubuntu下搜狗输入法乱码
    从命令行控制计算机屏幕
    CPU风扇转速异常
  • 原文地址:https://www.cnblogs.com/xiangniu/p/4255314.html
Copyright © 2011-2022 走看看