.net c#将 byte[] 转换为字符串并再次返回

Convert byte[] to string and back again
2021-12-04
  •  译文(汉语)
  •  原文(英语)

我有一个应用程序将数据库中请求的 IP 地址作为 varbinary(16) 存储在此处描述的方式中:Byte Array Size for a IPv6 IP Address.

我需要将 IP 地址从一台服务器传递到另一台服务器.出于这个原因,我不能仅仅依赖于 Request 对象.我的问题是,如果我将 IP 地址作为字节 [],如何将其编码为字符串,然后再次将其解码为字节 []?我总是对 ASCII、UTF8、Unicode 等编码感到困惑.

非常感谢!

解决过程1
var ipString = (new IPAddress(myBytes)).ToString()

然后在另一端

var addressBytes = IPAddress.Parse(ipString).GetAddressBytes();
解决过程2

对于稍微更用户友好的字符串表示形式,您可以使用Base64

str = System.Convert.ToBase64String(bytes);
bytes = System.Convert.FromBase64String(str);

I have an application that is storing the IP Addresses of requests in the database as a varbinary(16) in a manner described here: Byte Array Size for a IPv6 IP Address.

I need to pass the IP Address from one server to another. For that reason, I cannot just rely on the Request object. My question is, if I have the IP Address as a byte[], how do I encode it as a string and then decode it as a byte[] again? I always get confused with the ASCII, UTF8, Unicode, etc. encodings.

Thank you so much!

Solutions1
var ipString = (new IPAddress(myBytes)).ToString()

then at the other end

var addressBytes = IPAddress.Parse(ipString).GetAddressBytes();
Solutions2

For a slightly more user-friendly string representation, you can use Base64

str = System.Convert.ToBase64String(bytes);
bytes = System.Convert.FromBase64String(str);
转载于:https://stackoverflow.com/questions/15207731/convert-byte-to-string-and-back-again

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入