我怎么能连接code 1和0运输的字符串? [英] How could I encode a string of 1s and 0s for transport?

查看:121
本文介绍了我怎么能连接code 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".

有关运输及仓储然而,这似乎是一种浪费。什么是EN $ C $作为一个较短的字符串最简单的方法C此?

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

我猜这是pretty微不足道,但我不知道从哪里开始寻找。

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

倒车操作非常相似。

Reversing the operation is very similar.

如果您需要将数据作为字符串传递,你可以基地64 EN $ C $ç产生的字节数组。

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

您也可以考虑在内存中保持它以这种形式了。这将大大不是将其存储为每个数字存储为一个2字节字符的字符串更有效。比你需要为存储数据,你使用的是大约16倍更多的内存。该disadvtange是,它是稍难以这种形式来使用,所以如果你有足够的内存,那么你目前做的可能只是罚款。

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.

这篇关于我怎么能连接code 1和0运输的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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