感谢@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 转换为字符串到字节数组而不分配任何字符串的目标。