问题描述
我想:
- 生成的字节数组。
- 转换的字节数组为base64
- 将其转换的base64字符串返回到一个字节数组。
我试过了几个解决方案,例如那些在这个<一个href=\"http://stackoverflow.com/questions/8645088/how-to-de$c$c-a-string-of-text-from-a-base64-to-a-byte-array-and-the-get-the-st\">question.
由于某些原因,最初和最后的字节数组不匹配。下面是使用code:
使用(RNGCryptoServiceProvider RNG =新RNGCryptoServiceProvider())
{
字节[] = originalArray新的字节[32];
rng.GetBytes(键);
字符串temp_inBase64 = Convert.ToBase64String(originalArray);
字节[] = temp_backToBytes Encoding.UTF8.GetBytes(temp_inBase64);
}
我的问题是:
-
为什么originalArray和temp_backToBytes不匹配? (originalArray具有长度为32,temp_backToBytes有44的长度,但它们的值也不同)
-
是否有可能来回转换,如果是这样,我怎么做到这一点?
究其原因,EN codeD阵列长了大约四分之一是基于64位编码只使用六位每字节;这是其存在的理由 - 为en code任意数据,可能与零和其他非打印字符,在某种程度上适合于仅通过ASCII通道,如电子邮件交换
您得到您的原始数组的回复是通过使用 Convert.FromBase64String
的方式:
字节[] = temp_backToBytes Convert.FromBase64String(temp_inBase64);
I am trying to:
- Generate a byte array.
- Convert that byte array to base64
- Convert that base64 string back to a byte array.
I've tried out a few solutions, for example those in this question.
For some reason the initial and final byte arrays do not match. Here is the code used:
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] originalArray = new byte[32];
rng.GetBytes(key);
string temp_inBase64 = Convert.ToBase64String(originalArray);
byte[] temp_backToBytes = Encoding.UTF8.GetBytes(temp_inBase64);
}
My questions are:
Why do "originalArray" and "temp_backToBytes" not match? (originalArray has length of 32, temp_backToBytes has a length of 44, but their values are also different)
Is it possible to convert back and forth, and if so, how do I accomplish this?
The reason the encoded array is longer by about a quarter is that base-64 encoding uses only six bits out of every byte; that is its reason of existence - to encode arbitrary data, possibly with zeros and other non-printable characters, in a way suitable for exchange through ASCII-only channels, such as e-mail.
The way you get your original array back is by using Convert.FromBase64String
:
byte[] temp_backToBytes = Convert.FromBase64String(temp_inBase64);
这篇关于从字节数组转换为Base64和回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!