不使用字符串实现Int64.ToString

时间:2013-10-25 16:57:24

标签: c#

我遇到需要将long转换为字符数组而不分配任何新对象的情况。我想模仿long.ToString()中的内容而不实际创建一个字符串对象,基本上 - 而是将字符插入到预定义的数组中。我觉得这应该是非常简单的,但我找不到任何例子 - C#中的所有内容都使用类似ToString或String.Format的东西,C ++中的所有内容都使用stringstream,sprintf或ltoa。有什么想法吗?

编辑:稍微澄清一下,这是经常调用的代码的一个关键部分的一部分,它无法承受垃圾收集,因此我不想分配额外的字符串。输出实际上放在一个字节数组中 - 但是这个数据的接收者需要一个字符表示这个long的字节数组,所以我试图通过转换为字符串格式来减少垃圾收集而不分配新对象。

1 个答案:

答案 0 :(得分:0)

感谢@SLaks的想法和@gypsoCoder指向我的相关答案。这就是诀窍:

  private static byte[] chars = new byte[] { (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9' };

  /// <summary>
  /// Converts a long to a byte, in string format
  /// 
  /// This method essentially performs the same operation as ToString, with the output being a byte array,
  /// rather than a string
  /// </summary>
  /// <param name="val">long integer input, with as many or fewer digits as the output buffer length</param>
  /// <param name="longBuffer">output buffer</param>
  private void ConvertLong(long val, byte[] longBuffer)
  {
     // The buffer must be large enough to hold the output

     long limit = (long)Math.Pow(10, longBuffer.Length - 1);
     if (val >= limit * 10)
     {
        throw new ArgumentException("Value will not fit in output buffer");
     }

     // Note: Depending on your output expectation, you may do something different to initialize the data here.
     // My expectation was that the string would be at the "front" in string format, e.g. the end of the array, with '0' in any extra space

     int bufferIndex = 1;
     for (long longIndex = limit; longIndex > val; longIndex /= 10)
     {
        longBuffer[longBuffer.Length - bufferIndex] = 0;
        ++bufferIndex;
     }

     // Finally, loop through the digits of the input, converting them from a static buffer of byte values

     while (val > 0)
     {
        longBuffer[longBuffer.Length - bufferIndex] = chars[val % 10];
        val /= 10;
        ++bufferIndex;
     }
  }

我应该注意,这只接受正数,并且不对该数据或其他任何内容进行任何验证。只是一个基本算法,用于实现将long转换为字符串到字节数组而不分配任何字符串的目标。

相关问题