Span<byte> MySpan = stackalloc byte[] { 12, 21, 32 };
MessageBox.Show(Convert.ToBase64String(MySpan.ToArray()));
This block of code is the method I tried with success, but ToArray allocates memory, for this I want to find a way to be able to convert the Span of Bytes into a Convertable base64 or atleast ToList since has a more flexible constraint. Is there any way to do this? Without the use of the ToArray method, I'm very new to Span by the way Thank you in advance.
CodePudding user response:
.Net 4.8 does not contain methods supporting Span/Memory, since these where added later. So your options would be
- Update your code to .Net core 2.1.
- Find third party implementation.
- Write your own ToBase64 method.
- Reuse buffers
With regard to the forth point, if you have any memory issue it is probably because you are doing this repeatedly. If so it is usually a good idea to reuse buffers as much as possible. So you can use Span.CopyTo to copy your data from one span to a span wrapping your buffer. You can then use one of the ToBase64String overloads that takes a length to specify how many bytes to convert. But even if you do this the strings will also need allocation, so you might want something like the Base64.EncodeToUtf8 method in .Net core 2.1.