如何编码1和0的字符串进行传输? [英] How could I encode a string of 1s and 0s for transport?

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

问题描述

对于遗传算法应用程序,我使用的是二进制字符串的全部负载。大多数时候,他们以字面意思采取 01001010110 的形式,以便他们可以交配,变异和交叉。



然而,对于运输和存储,这似乎是浪费的。把这个编码成一个较短的字符串的最简单的方法是什么?



我猜这个很简单,但是我不知道从哪里开始看。 >

更新:我实际上需要使用另一个字符串:其中一个传输请求将是GET请求。

解决方案

最简单的方法是把每个数字放在一起。每组8位可以存储在一个字节中。然后你可以发送一个字节流。您还需要存储原始字符串的长度,以便您可以区分0和00。



这里有一种方式可以编写转换从字符串到字节数组:

  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;
}
}
返回结果;
}

逆转操作非常相似。



如果您需要以字符串形式传输数据,可以基础64编码生成的字节数组。



您可能还想考虑将其保存在内存中。这将比存储为每个数字作为2字节字符的字符串更有效。您使用的存储空间大约是存储数据的16倍。不利之处在于,以这种形式使用起来稍微困难一点,所以如果你有足够的记忆,那么你目前正在做的事情可能会很好。


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.

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

解决方案

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

Reversing the operation is very similar.

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

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的字符串进行传输?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆