0
我必須創建用於檢索數據的條形碼。實際字符串的最大大小是60.但我需要打印的條碼最多12個字符。如何使用另一個長字符串創建最多12個字符的加密字符串
我可以加密長字符串來簡短和解密再次使用C#或JavaScript?
我必須創建用於檢索數據的條形碼。實際字符串的最大大小是60.但我需要打印的條碼最多12個字符。如何使用另一個長字符串創建最多12個字符的加密字符串
我可以加密長字符串來簡短和解密再次使用C#或JavaScript?
如果您的文本只有ASCII字符,那麼您可以通過將多個ASCII字符實際存儲在單個UTF8字符中,將其減少一半。
這將是實際代碼:
public static class ByteExtensions
{
private const int BYTE_SIZE = 8;
public static byte[] Encode(this byte[] data)
{
if (data.Length == 0) return new byte[0];
int length = 3 * BYTE_SIZE;
BitArray source = new BitArray(data);
BitArray encoded = new BitArray(length);
int sourceBit = 0;
for (int i = (length/BYTE_SIZE); i > 1; i--)
{
for (int j = 6; j > 0; j--) encoded[i * BYTE_SIZE - 2 - j] = source[sourceBit++];
encoded[i * BYTE_SIZE - 1] = true;
encoded[i * BYTE_SIZE - 2] = false;
}
for (int i = BYTE_SIZE - 1; i > BYTE_SIZE - 1 - (length/BYTE_SIZE); i--) encoded[i] = true;
encoded[BYTE_SIZE - 1 - (length/BYTE_SIZE)] = false;
for (int i = 0; i <= BYTE_SIZE - 2 - (length/BYTE_SIZE); i++) encoded[i] = source[sourceBit++];
byte[] result = new byte[length/BYTE_SIZE];
encoded.CopyTo(result, 0);
return result;
}
public static byte[] Decode(this byte[] data)
{
if (data.Length == 0) return new byte[0];
int length = 2 * BYTE_SIZE;
BitArray source = new BitArray(data);
BitArray decoded = new BitArray(length);
int currentBit = 0;
for (int i = 3; i > 1; i--) for (int j = 6; j > 0; j--) decoded[currentBit++] = source[i * BYTE_SIZE - 2 - j];
for (int i = 0; i <= BYTE_SIZE - 5; i++) decoded[currentBit++] = source[i];
byte[] result = new byte[length/BYTE_SIZE];
decoded.CopyTo(result, 0);
return result;
}
}
public static class StringExtensions
{
public static string Encode(this string text)
{
byte[] ascii = Encoding.ASCII.GetBytes(text);
List<byte> encoded = new List<byte>();
for (int i = 0; i < ascii.Length; i += 2) encoded.AddRange(new byte[] { ascii[i], (i + 1) < ascii.Length ? ascii[i + 1] : (byte)30 }.Encode());
return Encoding.UTF8.GetString(encoded.ToArray());
}
public static string Decode(this string text)
{
byte[] utf8 = Encoding.UTF8.GetBytes(text);
List<byte> decoded = new List<byte>();
for (int i = 0; i < utf8.Length - 2; i += 3) decoded.AddRange(new byte[] { utf8[i], utf8[i + 1], utf8[i + 2] }.Decode());
return Encoding.ASCII.GetString(decoded.ToArray());
}
}
一個例子:
string text = "This is some large text which will be reduced by half!";
string encoded = text.Encode();
您將無法以使其控制檯窗口上,因爲文本現在UTF8,但這是什麼encoded
舉行:桔獩槧潳敭氠牡敧琠硥⁴桷捩楷汬戠敲畤散禰栠污Ⅶ
正如你所看到的,我們設法編碼一個54
字符長字符串到只有27
個字符。
實際上,你可以通過做拿回原始字符串:
string decoded = encoded.Decode();
我認爲你正在尋找壓縮比加密。 –
您是否考慮過創建一個查找表,將<12個字符的鍵作爲您的條形碼值,然後在表中找到實際的60個字符的字符串?我對壓縮算法並不熟悉 - 從60到不超過12個字符看起來相當不錯。 – ohiodoug
@ohiodoug,謝謝你的建議。在目前的情況下,創建表格不是一種選擇:-(。 – Kathiravan