我如何编码一串 1 和 0 用于传输?

How could I encode a string of 1s and 0s for transport?(我如何编码一串 1 和 0 用于传输?)

本文介绍了我如何编码一串 1 和 0 用于传输?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于遗传算法应用程序,我使用了一整套二进制字符串.大多数情况下,它们实际上采用 01001010110 的形式,以便它们可以交配、变异和交叉".

For a genetic algorithm application, I'm using a whole load of binary strings. Most of the time they literally take the form of 01001010110, so that they can be mated, mutated and "crossed-over".

然而,对于运输和存储来说,这似乎是一种浪费.将其编码为较短字符串的最简单方法是什么?

For transport and storage however, this seems wasteful. What's the simplest way to encode this as a shorter string?

我猜这很简单,但我不确定从哪里开始.

I'm guessing this is pretty trivial, but I'm not sure where to start looking.

更新:我实际上需要以另一个字符串结尾:其中一个传输请求将是 GET 请求.

Update: I actually need to end up with another string: one of the transport requests will be GET requests.

推荐答案

最简单的方法是取每个数字并将其视为一个位.每组 8 位可以存储在一个字节中.然后您可以将其作为字节流发送.您还需要存储原始字符串的长度,以便区分0"和00".

The simplest would be to take each digit and treat it as a bit. Each group of 8 bits can be stored in a byte. Then you can send it as a stream of bytes. You will also need to store the length of the original string so that you can distinguish between "0" and "00".

这是一种将字符串转换为字节数组的方法:

Here is one way you could write the conversion from string to a byte array:

byte[] convertToBytes(string s)
{
    byte[] result = new byte[(s.Length + 7) / 8];

    int i = 0;
    int j = 0;
    foreach (char c in s)
    {
        result[i] <<= 1;
        if (c == '1')
            result[i] |= 1;
        j++;
        if (j == 8)
        {
            i++;
            j = 0;
        }
    }
    return result;
}

反转操作非常相似.

如果您需要将数据作为字符串传输,您可以base 64 编码 得到的字节数组.

If you need to transmit the data as a string you can base 64 encode the resulting byte array.

您可能还想考虑将它以这种形式保存在内存中.这将比将其存储为每个数字存储为 2 字节字符的字符串更有效.您使用的内存大约是存储数据所需的 16 倍.缺点是这种形式使用起来稍微困难一些,所以如果你有足够的内存,那么你现在正在做的事情可能就可以了.

You may also want to consider keeping it in this form in memory too. This will be much more efficient than storing it as a string where each digit is stored as a 2 byte character. You are using roughly 16 times more memory than you need to for storing your data. The disadvtange is that it is slightly more difficult to use in this form, so if you have enough memory then what you are currently doing might be just fine.

这篇关于我如何编码一串 1 和 0 用于传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我如何编码一串 1 和 0 用于传输?

基础教程推荐