アイデアを提供してくれた@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 を文字列からバイト配列に変換するという目標を達成するための基本的なアルゴリズムです。