UTF8编码为base64字符串并存储到数据库
我目前正在尝试在将数据存储到数据库之前对其进行编码。
try
{
byte[] byteEncString = new byte[_strToConvert.Length];
byteEncString = System.Text.Encoding.UTF8.GetBytes(_strToConvert);
string strEncoded = Convert.ToBase64String(byteEncString);
return strEncoded;
}
有谁知道15个字符的字符串通过utf8和base64string编码后会有多长?另外,有上限吗?我在 sql server 上的字段只有 50,我想将其限制在该范围内。想法?
I'm currently trying to encode data before storing it to my database.
try
{
byte[] byteEncString = new byte[_strToConvert.Length];
byteEncString = System.Text.Encoding.UTF8.GetBytes(_strToConvert);
string strEncoded = Convert.ToBase64String(byteEncString);
return strEncoded;
}
Does anybody know how long a 15 character string will be after it is encoded via utf8 and base64string? Also, is there a max? My field on sql server is only 50 and i want to limit it in that range. Thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
嗯,一方面,创建一个字节数组然后忽略它是没有意义的 - 因此您的代码会更简单,因为:
当 UTF-8 编码时,.NET
char
最终可以为 3 个字节1,因此最大长度为 45 字节。但是,base64 将 3 个字节转换为 4 个字符,因此结果给出最大 60 个字符的 base64 编码字符串。1 这是因为任何不在基本多语言平面中的字符都被表示为代理对。该对最终将是 4 个字节,但需要 2 个输入字符,因此在这种情况下,平均“每个
char
字节”仅为 2。Well, for one thing there's no point in creating a byte array and then ignoring it - so your code would be simpler as:
A .NET
char
can end up as 3 bytes when UTF-8 encoded1, so that gets to a 45 byte maximum. However, base64 converts 3 bytes to 4 characters, so that gives a 60 character maximum base64 encoded string as the result.1 This is because any characters not in the basic multilingual plane are represented as a surrogate pair. That pair would end up as 4 bytes, but having taken 2 input characters, so the average "bytes per
char
" in that case is only 2.