感謝@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轉換爲字符串而不分配任何字符串的目標。
使用mod和division來獲取每個數字的值。 – SLaks
請添加一些你已經嘗試過的代碼。 – Alexandre
@SLaks duh,謝謝,我會試試看。 – Deeko