Home > OS >  How to add (concatenate) two Google.Protobuf.ByteStrings? C#
How to add (concatenate) two Google.Protobuf.ByteStrings? C#

Time:08-03

I had not found a way of adding two bytestrings in google documentation. I tried to convert them to strings, concatenate, than convert back. But it gets stuck on conversion back to ByteString.

if (someList.Count > 3)
{
    var bigString = "";
    for (int i = 0; i < someList.Count; i  )
    {
        string partString= someList.ElementAt(i).ToBase64();
        bigString  = partString;
        Logger.Write($"{i}");
    }
    Logger.Write("here");
    var chunk = ByteString.FromBase64(bigString);
    Logger.Write("here2");
    SomeFunc(chunk);
    someList.Clear();
}

It gets "here", but never to "here2".

UPD: ByteStrings in someList contain WaveIn audioData

CodePudding user response:

I would definitely not suggest converting to base64 and back - there's no need for that, and it causes issues as base64 strings aren't naturally joinable like this due to padding.

It looks like you're not actually trying to concatenate two ByteStrings, but some arbitrary number. I'd suggest writing them all to a MemoryStream, then creating a new ByteString from that:

using var tempStream = new MemoryStream();
foreach (var byteString in someList)
{
    byteString.WriteTo(tempStream);
}
tempStream.Position = 0;
var combinedString = ByteString.FromStream(tempStream);
  • Related