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