博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【转】Contrary to the answers here, you DON'T need to worry about encoding!
阅读量:4589 次
发布时间:2019-06-09

本文共 1257 字,大约阅读时间需要 4 分钟。

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.

转载于:https://www.cnblogs.com/xiangniu/p/4255314.html

你可能感兴趣的文章
Kill_UiAutomator
查看>>
HDU 2157 How many ways??
查看>>
Floyd最短路径
查看>>
方法重载和重写的区别
查看>>
块状元素和内联元素
查看>>
nav元素
查看>>
内存对齐
查看>>
HTML及资源是如何load的
查看>>
虚拟机apache启动
查看>>
【Linux】Centos下安装ffmpeg
查看>>
VSCode使用随笔
查看>>
MySQL 常用命令
查看>>
nginx FastCGI配置 No input file specified
查看>>
iOS - 拓展
查看>>
Windows命令远程执行工具Winexe
查看>>
XamarinAndroid组件教程RecylerView动画组件使用动画(3)
查看>>
linux vim 配置 go 开发环境
查看>>
week 6 CORS
查看>>
Openstack Neutron:二层技术和实现
查看>>
组合设计模式
查看>>