0

您如何将段落转换为十六进制表示法,然后再转换回其原始字符串形式?

(C#)

附注:将字符串放入十六进制格式是否会在不使用硬核收缩算法的情况下最大程度地收缩它?

4

5 回答 5

6

“十六进制表示法”到底是什么意思?这通常是指编码二进制数据,而不是文本。您需要以某种方式对文本进行编码(例如使用 UTF-8),然后通过将每个字节转换为一对字符将二进制数据编码为文本。

using System;
using System.Text;

public class Hex
{
    static void Main()
    {
        string original = "The quick brown fox jumps over the lazy dog.";

        byte[] binary = Encoding.UTF8.GetBytes(original);
        string hex = BytesToHex(binary);
        Console.WriteLine("Hex: {0}", hex);
        byte[] backToBinary = HexToBytes(hex);

        string restored = Encoding.UTF8.GetString(backToBinary);
        Console.WriteLine("Restored: {0}", restored);
    }

    private static readonly char[] HexChars = "0123456789ABCDEF".ToCharArray();

    public static string BytesToHex(byte[] data)
    {
        StringBuilder builder = new StringBuilder(data.Length*2);
        foreach(byte b in data)
        {
            builder.Append(HexChars[b >> 4]);
            builder.Append(HexChars[b & 0xf]);
        }
        return builder.ToString();
    }

    public static byte[] HexToBytes(string text)
    {
        if ((text.Length & 1) != 0)
        {
            throw new ArgumentException("Invalid hex: odd length");
        }
        byte[] ret = new byte[text.Length/2];
        for (int i=0; i < text.Length; i += 2)
        {
            ret[i/2] = (byte)(ParseNybble(text[i]) << 4 | ParseNybble(text[i+1]));
        }
        return ret;
    }

    private static int ParseNybble(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c-'0';
        }
        if (c >= 'A' && c <= 'F')
        {
            return c-'A'+10;
        }
        if (c >= 'a' && c <= 'f')
        {
            return c-'A'+10;
        }
        throw new ArgumentOutOfRangeException("Invalid hex digit: " + c);
    }
}

不,这样做根本不会缩小它。恰恰相反——你最终会得到更多的文字!但是,您可以压缩二进制形式。在将任意二进制数据表示为文本方面,Base64 比普通十六进制更有效。使用Convert.ToBase64StringConvert.FromBase64String进行转换。

于 2008-10-20T19:41:51.573 回答
1
public string ConvertToHex(string asciiString)
{
    string hex = "";
    foreach (char c in asciiString)
    {
        int tmp = c;
        hex += String.Format("{0:x2}", (uint)System.Convert.ToUInt32(tmp.ToString()));
    }
    return hex;
}
于 2008-10-20T19:41:37.517 回答
0

虽然我对 C# 实现帮不上忙,但我强烈推荐LZW作为一种易于实现的数据压缩算法供您使用。

于 2008-10-20T19:47:17.287 回答
0

如果我们问:你真正想做什么?也许可以更快地得到答案。将普通字符串转换为十六进制表示的字符串似乎是错误的方法,除非您正在为网络制作十六进制/编码教程。

于 2008-10-21T20:45:17.280 回答
0
static byte[] HexToBinary(string s) {
  byte[] b = new byte[s.Length / 2];
  for (int i = 0; i < b.Length; i++)
    b[i] = Convert.ToByte(s.Substring(i * 2, 2), 16);
  return b;
}
static string BinaryToHex(byte[] b) {
  StringBuilder sb = new StringBuilder(b.Length * 2);
  for (int i = 0; i < b.Length; i++)
    sb.Append(Convert.ToString(256 + b[i], 16).Substring(1, 2));
  return sb.ToString();
}
于 2009-06-30T18:17:52.210 回答