本文介绍了从字节数组转换为Base64和回的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想:


  1. 生成的字节数组。

  2. 转换的字节数组为base64

  3. 将其转换的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);
    }

我的问题是:


  1. 为什么originalArray和temp_backToBytes不匹配? (originalArray具有长度为32,temp_backToBytes有44的长度,但它们的值也不同)


  2. 是否有可能来回转换,如果是这样,我怎么做到这一点?



解决方案

究其原因,EN codeD阵列长了大约四分之一是基于64位编码只使用六位每字节;这是其存在的理由 - 为en code任意数据,可能与零和其他非打印字符,在某种程度上适合于仅通过ASCII通道,如电子邮件交换

您得到您的原始数组的回复是通过使用 Convert.FromBase64String 的方式:

 字节[] = temp_backToBytes Convert.FromBase64String(temp_inBase64);

I am trying to:

  1. Generate a byte array.
  2. Convert that byte array to base64
  3. 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:

  1. 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)

  2. 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和回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 00:34
查看更多