2013-10-25 49 views
0

我有一種情況,我需要將一個long轉換爲字符數組而不分配任何新的對象。我想模仿long.ToString()中的內容,而不實際創建一個字符串對象,基本上 - 將字符插入到預定義的數組中。我覺得這應該是非常簡單的,但我找不到任何示例 - C#中的所有東西都使用類似ToString或String.Format的東西,C++中的所有東西都使用stringstream,sprintf或ltoa。有任何想法嗎?不使用字符串實現Int64.ToString

編輯:爲了澄清一點,這是經常調用的代碼的關鍵部分的一部分,它不能承受垃圾回收,因此我不想分配額外的字符串。輸出實際上被放置到一個字節數組中 - 但是這個數據的接收者需要一個長字符表示的字節數組,所以我試圖通過在不分配新對象的情況下轉換爲字符串格式來減少垃圾回收。

+5

使用mod和division來獲取每個數字的值。 – SLaks

+0

請添加一些你已經嘗試過的代碼。 – Alexandre

+0

@SLaks duh,謝謝,我會試試看。 – Deeko

回答

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轉換爲字符串而不分配任何字符串的目標。

相關問題