Skoder
Skoder

Reputation: 4053

Convert from Byte array to a List

I'm converting a List<string> into a byte array like this:

Byte[] bArray = userList
                .SelectMany(s => System.Text.Encoding.ASCII.GetByte(s))
                .ToArray();

How can I convert it back to a List<string>? I tried using ASCII.GetString(s) in the code above, but GetString expected a byte[], not a single byte.

Upvotes: 0

Views: 9663

Answers (4)

brunnerh
brunnerh

Reputation: 185553

As a bit of a sidenote, if you preserve the zero-byte string termination you can easily concatenate the strings and extract all information, e.g.

Byte[] bArray = userList
    .SelectMany(s => System.Text.Encoding.ASCII.GetBytes(s + '\0')) // Add 0 byte
    .ToArray();

List<string> names = new List<string>();
for (int i = 0; i < bArray.Length; i++)
{
    int end = i;
    while (bArray[end] != 0) // Scan for zero byte
        end++;
    var length = end - i;
    var word = new byte[length];
    Array.Copy(bArray, i, word, 0, length);
    names.Add(ASCIIEncoding.ASCII.GetString(word));
    i += length;
}

Upvotes: 3

Mark Byers
Mark Byers

Reputation: 839214

It's not possible to reverse your algorithm.

The problem can be seen if you consider what happens when you have two users called "ab" and "c". This will give the exact same bytes as if you have two users called "a" and "bc". There is no way to distinguish between these two cases with your approach.

Instead of inventing your own serialization format you could just the serialization that is built into the .NET framework, such as the BinaryFormatter.

Upvotes: 5

Gustavo F
Gustavo F

Reputation: 2206

You can't do this since the delimiters of the array structure were lost in the SelectMany method.

Upvotes: 1

ChrisWue
ChrisWue

Reputation: 19070

You need to insert a delimter between your strings so that you can split the big byte array back into the original users. The delimiter should be a character which cannot be part of a user name.

Example (assuming | cannot be part of a user name):

var bytes = System.Text.Encoding.ASCII.GetByte(string.Join("|", userList.ToArray()));

Upvotes: 1

Related Questions