简体   繁体   中英

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.

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 .

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

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;
}

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()));

您无法执行此操作,因为SelectMany方法中丢失了数组结构的分隔符。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM