問題描述
對于遺傳算法應(yīng)用程序,我使用了一整套二進(jìn)制字符串.大多數(shù)情況下,它們實(shí)際上采用 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".
然而,對于運(yùn)輸和存儲來說,這似乎是一種浪費(fèi).將其編碼為較短字符串的最簡單方法是什么?
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.
更新:我實(shí)際上需要以另一個字符串結(jié)尾:其中一個傳輸請求將是 GET 請求.
Update: I actually need to end up with another string: one of the transport requests will be GET requests.
推薦答案
最簡單的方法是取每個數(shù)字并將其視為一個位.每組 8 位可以存儲在一個字節(jié)中.然后您可以將其作為字節(jié)流發(fā)送.您還需要存儲原始字符串的長度,以便區(qū)分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".
這是一種將字符串轉(zhuǎn)換為字節(jié)數(shù)組的方法:
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;
}
反轉(zhuǎn)操作非常相似.
如果您需要將數(shù)據(jù)作為字符串傳輸,您可以base 64 編碼 得到的字節(jié)數(shù)組.
If you need to transmit the data as a string you can base 64 encode the resulting byte array.
您可能還想考慮將它以這種形式保存在內(nèi)存中.這將比將其存儲為每個數(shù)字存儲為 2 字節(jié)字符的字符串更有效.您使用的內(nèi)存大約是存儲數(shù)據(jù)所需的 16 倍.缺點(diǎn)是這種形式使用起來稍微困難一些,所以如果你有足夠的內(nèi)存,那么你現(xiàn)在正在做的事情可能就可以了.
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.
這篇關(guān)于我如何編碼一串 1 和 0 用于傳輸?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!