11

(在 .NET 中)我将任意二进制数据存储在byte[](例如图像)中。现在,我需要将该数据存储在一个字符串中(遗留 API 的“注释”字段)。是否有将这种二进制数据打包字符串的标准技术?通过“打包”,我的意思是对于任何相当大的随机数据集,bytes.Length/2与packed.Length 大致相同;因为两个字节或多或少是一个字符。

两个“明显”的答案不符合所有标准:

string base64 = System.Convert.ToBase64String(bytes)

没有非常有效地使用字符串,因为它只使用大约 60,000 个可用字符中的 64 个字符(我的存储是System.String)。一起去

string utf16 = System.Text.Encoding.Unicode.GetString(bytes)

更好地利用了string,但它不适用于包含无效 Unicode 字符的数据(比如不匹配的代理对)。 这篇 MSDN 文章展示了这种精确(差)的技术。

让我们看一个简单的例子:

byte[] bytes = new byte[] { 0x41, 0x00, 0x31, 0x00};
string utf16 = System.Text.Encoding.Unicode.GetString(bytes);
byte[] utf16_bytes = System.Text.Encoding.Unicode.GetBytes(utf16);

在这种情况下bytesutf16_bytes是相同的,因为原始字节是 UTF-16 字符串。使用 base64 编码执行相同的过程会得到 16 个成员的base64_bytes数组。

现在,使用无效的 UTF-16 数据重复该过程:

byte[] bytes = new byte[] { 0x41, 0x00, 0x00, 0xD8};

您会发现utf16_bytes与原始数据不匹配。

我编写了在无效 Unicode 字符之前使用 U+FFFD 作为转义的代码;它有效,但我想知道是否有比我自己制作的更标准的技术。更不用说,我不喜欢将DecoderFallbackException作为检测无效字符的方式。

我想您可以将其称为“基本 BMP”或“基本 UTF-16”编码(使用 Unicode 基本多语言平面中的所有字符)。是的,理想情况下,我会遵循Shawn Steele 的建议并传递byte[]


我将接受 Peter Housel 的建议作为“正确”答案,因为他是唯一一个接近建议“标准技术”的人。


编辑base16k 看起来更好。Jim Beveridge 有一个实现

4

7 回答 7

12

我可以建议你使用base64 吗?它可能不是最有效的存储方式,但它确实有它的好处:

  1. 您对代码的担忧已经结束。
  2. 如果有的话,您与其他播放器的兼容性问题最少。
  3. 如果在转换、导出、导入、备份、恢复等过程中将编码字符串视为 ASCII,您也不会有任何问题。
  4. 如果您曾经摔死或最终在公共汽车或其他东西下,任何接触到评论字段的程序员都会立即知道它是base64,而不是假设它都是加密的或其他东西。
于 2009-03-19T14:43:18.687 回答
5

阅读您的问题后,我偶然发现了Base16k 。严格来说不是一个标准,但它似乎运行良好并且很容易在 C# 中实现。

于 2009-04-27T15:08:18.357 回答
3

首先,请记住 Unicode 并不意味着 16 位。System.String 在内部使用 UTF-16 的事实既不存在也不存在。Unicode 字符是抽象的——它们只能通过编码获得位表示。

你说“我的存储是一个 System.String”——如果是这样,你就不能谈论位和字节,只能谈论 Unicode 字符。System.String 当然有它自己的内部编码,但(理论上)可能会有所不同。

顺便说一句,如果您认为 System.String 的内部表示对于 Base64 编码的数据来说内存效率太低,您为什么不担心拉丁/西方字符串呢?

如果要将二进制数据存储在 System.String 中,则需要位和字符集合之间的映射。

选项 A:有一个预制的 Base64 编码形状。正如您所指出的,这对每个字符编码六位数据。

选项 B:如果您想为每个字符打包更多位,那么您需要创建一个包含 128、256、512 等 Unicode 字符的数组(或编码),并为每个字符打包 7、8、9 等位数据特点。这些字符必须是真正的 Unicode 字符。

为了简单地回答您的问题,是的,有一个标准,它是 Base64 编码。

这是一个真正的问题吗?您是否有性能数据来支持您不使用 Base64 的想法?

于 2009-03-21T13:16:40.943 回答
2

您可以将二进制数据视为UTF-8b。UTF-8b 编码假定字节是 UTF-8 多字节序列,但是对于不是的东西有一个备用编码。

于 2009-03-15T03:30:51.557 回答
1

这是 Jim Beveridge 的 C++实现的 C# 版本:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;


//
// Base16k.cpp : Variant of base64 used to efficiently encode  binary into Unicode UTF16 strings. Based on work by
// Markus Scherer at https://sites.google.com/site/markusicu/unicode/base16k
//
// This code is hereby placed in the Public Domain.
// Jim Beveridge, November 29, 2011.
//
// C# port of http://qualapps.blogspot.com/2011/11/base64-for-unicode-utf16.html
// This code is hereby placed in the Public Domain.
// J. Daniel Smith, February 23, 2015
//

namespace JDanielSmith
{
    public static partial class Convert
    {
        /// <summary>
        /// Encode a binary array into a Base16k string for Unicode.
        /// </summary>
        public static string ToBase16kString(byte[] inArray)
        {
            int len = inArray.Length;

            var sb = new StringBuilder(len*6/5);
            sb.Append(len);

            int code = 0;

            for (int i=0; i<len; ++i)
            {
                byte byteValue = inArray[i];
                switch (i%7)
                {
                case 0:
                    code = byteValue<<6;
                    break;

                case 1:
                    code |= byteValue>>2;
                    code += 0x5000;
                    sb.Append(System.Convert.ToChar(code));
                    code = (byteValue&3)<<12;
                    break;

                case 2:
                    code |= byteValue<<4;
                    break;

                case 3:
                    code |= byteValue>>4;
                    code+=0x5000;
                    sb.Append(System.Convert.ToChar(code));
                    code = (byteValue&0xf)<<10;
                    break;

                case 4:
                    code |= byteValue<<2;
                    break;

                case 5:
                    code|=byteValue>>6;
                    code+=0x5000;
                    sb.Append(System.Convert.ToChar(code));
                    code=(byteValue&0x3f)<<8;
                    break;

                case 6:
                    code|=byteValue;
                    code+=0x5000;
                    sb.Append(System.Convert.ToChar(code));
                    code=0;
                    break;
                }
            }

            // emit a character for remaining bits
            if (len%7 != 0) {
                code += 0x5000;
                sb.Append(System.Convert.ToChar(code));
            }

            return sb.ToString();
        }

        /// <summary>
        ///  Decode a Base16k string for Unicode into a binary array.
        /// </summary>
        public static byte[] FromBase16kString(string s)
        {
            // read the length
            var r = new Regex(@"^\d+", RegexOptions.None, matchTimeout: TimeSpan.FromMilliseconds(100));
            Match m = r.Match(s);
            if (!m.Success)
                return null;

            int length;
            if (!Int32.TryParse(m.Value, out length))
                return null;

            var buf = new List<byte>(length);

            int pos=0;  // position in s
            while ((pos < s.Length) && (s[pos] >= '0' && s[pos] <= '9'))
                ++pos;

            // decode characters to bytes
            int i = 0;    // byte position modulo 7 (0..6 wrapping around)
            int code=0;
            byte byteValue=0;

            while (length-- > 0)
            {
                if (((1<<i)&0x2b)!=0)
                {
                    // fetch another Han character at i=0, 1, 3, 5
                    if(pos >= s.Length)
                    {
                        // Too few Han characters representing binary data.
                        System.Diagnostics.Debug.Assert(pos < s.Length);
                        return null;
                    }

                    code=s[pos++]-0x5000;
                }

                switch (i%7)
                {
                case 0:
                    byteValue = System.Convert.ToByte(code>>6);
                    buf.Add(byteValue);
                    byteValue = System.Convert.ToByte((code&0x3f)<<2);
                    break;

                case 1:
                    byteValue |= System.Convert.ToByte(code>>12);
                    buf.Add(byteValue);
                    break;

                case 2:
                    byteValue = System.Convert.ToByte((code>>4)&0xff);
                    buf.Add(byteValue);
                    byteValue = System.Convert.ToByte((code&0xf)<<4);
                    break;

                case 3:
                    byteValue |= System.Convert.ToByte(code>>10);
                    buf.Add(byteValue);
                    break;

                case 4:
                    byteValue = System.Convert.ToByte((code>>2)&0xff);
                    buf.Add(byteValue);
                    byteValue = System.Convert.ToByte((code&3)<<6);
                    break;

                case 5:
                    byteValue |= System.Convert.ToByte(code>>8);
                    buf.Add(byteValue);
                    break;

                case 6:
                    byteValue = System.Convert.ToByte(code&0xff);
                    buf.Add(byteValue);
                    break;
                }

                // advance to the next byte position
                if(++i==7)
                    i=0;
            }

            return buf.ToArray();
        }
    }
}

namespace Base16kCS
{
    class Program
    {
        static void Main(string[] args)
        {
            var drand = new Random();

            // Create 500 different binary objects, then encode and decode them.
            // The first 16 objects will have length 0,1,2 ... 16 to test boundary conditions.
            for (int loop = 0; loop < 500; ++loop)
            {
                Console.WriteLine("{0}", loop);

                int dw = drand.Next(128000);
                var org = new List<byte>(dw);
                for (int i = 0; i < dw; ++i)
                    org.Add(Convert.ToByte(drand.Next(256)));

                if (loop < 16)
                    org = org.Take(loop).ToList();

                string wstr = JDanielSmith.Convert.ToBase16kString(org.ToArray());

                byte[] bin = JDanielSmith.Convert.FromBase16kString(wstr);

                System.Diagnostics.Debug.Assert(org.SequenceEqual(bin));
            }
        }
    }
}
于 2015-02-24T16:03:31.790 回答
0

我用直接 char 数组愚弄了,你的一个失败案例适用于我的实现。代码已经过很好的测试:所以先做你的测试。

您可以通过使用不安全的代码来加快速度。但我确信 UnicodeEncoding 一样慢(如果不是更慢的话)。

/// <summary>
/// Represents an encoding that packs bytes tightly into a string.
/// </summary>
public class ByteEncoding : Encoding
{
    /// <summary>
    /// Gets the Byte Encoding instance.
    /// </summary>
    public static readonly Encoding Encoding = new ByteEncoding();

    private ByteEncoding()
    {
    }

    public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex)
    {
        for (int i = 0; i < chars.Length; i++)
        {
            // Work out some indicies.
            int j = i * 2;
            int k = byteIndex + j;

            // Get the bytes.
            byte[] packedBytes = BitConverter.GetBytes((short) chars[charIndex + i]);

            // Unpack them.
            bytes[k] = packedBytes[0];
            bytes[k + 1] = packedBytes[1];
        }

        return chars.Length * 2;
    }

    public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex)
    {
        for (int i = 0; i < byteCount; i += 2)
        {
            // Work out some indicies.
            int j = i / 2;
            int k = byteIndex + i;

            // Make sure we don't read too many bytes.
            byte byteB = 0;
            if (i + 1 < byteCount)
            {
                byteB = bytes[k + 1];
            }

            // Add it to the array.
            chars[charIndex + j] = (char) BitConverter.ToInt16(new byte[] { bytes[k], byteB }, 0);
        }

        return (byteCount / 2) + (byteCount % 2); // Round up.
    }

    public override int GetByteCount(char[] chars, int index, int count)
    {
        return count * 2;
    }

    public override int GetCharCount(byte[] bytes, int index, int count)
    {
        return (count / 2) + (count % 2);
    }

    public override int GetMaxByteCount(int charCount)
    {
        return charCount * 2;
    }

    public override int GetMaxCharCount(int byteCount)
    {
        return (byteCount / 2) + (byteCount % 2);
    }
}

这是一些测试代码:

    static void Main(string[] args)
    {
        byte[] original = new byte[256];

        // Note that we can't tell on the decode side how
        // long the array was if the original length is
        // an odd number. This will result in an
        // inconclusive result.
        for (int i = 0; i < original.Length; i++)
            original[i] = (byte) Math.Abs(i - 1);

        string packed = ByteEncoding.Encoding.GetString(original);
        byte[] unpacked = ByteEncoding.Encoding.GetBytes(packed);

        bool pass = true;

        if (original.Length != unpacked.Length)
        {
            Console.WriteLine("Inconclusive: Lengths differ.");
            pass = false;
        }

        int min = Math.Min(original.Length, unpacked.Length);
        for (int i = 0; i < min; i++)
        {
            if (original[i] != unpacked[i])
            {
                Console.WriteLine("Fail: Invalid at a position {0}.", i);
                pass = false;
            }
        }

        Console.WriteLine(pass ? "All Passed" : "Failure Present");

        Console.ReadLine();
    }

该测试有效,但您将不得不使用您的 API 函数对其进行测试。

于 2009-03-19T10:04:33.270 回答
0

还有另一种解决此限制的方法:尽管我不确定它的效果如何。

首先,您需要弄清楚 API 调用期望的字符串类型以及该字符串的结构是什么。如果我举一个简单的例子,让我们考虑 .Net 字符串:

  • Int32 _长度;
  • 字节[]_数据;
  • 字节_终止符= 0;

为您的 API 调用添加重载,因此:

[DllImport("legacy.dll")]
private static extern void MyLegacyFunction(byte[] data);

[DllImport("legacy.dll")]
private static extern void MyLegacyFunction(string comment);

然后,当您需要调用字节版本时,您可以执行以下操作:

    public static void TheLegacyWisperer(byte[] data)
    {
        byte[] realData = new byte[data.Length + 4 /* _length */ + 1 /* _terminator */ ];
        byte[] lengthBytes = BitConverter.GetBytes(data.Length);
        Array.Copy(lengthBytes, realData, 4);
        Array.Copy(data, 0, realData, 4, data.Length);
        // realData[end] is equal to 0 in any case.
        MyLegacyFunction(realData);
    }
于 2009-03-19T10:26:13.030 回答