2013-08-20 89 views
1

我創建做單位轉換一類,特別字節來千字節,兆字節,千兆字節,等等。我與B一個enum通過PB,但由於某些原因1024^0不返回1,它不是正確地從字節轉換爲字節或字節爲千字節等X不計算爲1

這裏是我的類:

public static class UnitConversion 
{ 
    /// <summary> 
    /// 1024^n 
    /// </summary> 
    public enum ByteConversionConstant 
    { 
     B = 0, 
     KB = 1, 
     MB = 2, 
     GB = 3, 
     TB = 4, 
     PB = 5 
    } 

    public static string GetValueFromBytes(long bytes, 
          ByteConversionConstant constant) 
    { 
     int n = (int)constant; 
     long divisor = 1024^n; 
     return (bytes/divisor).ToString() + 
       Enum.GetName(typeof(ByteConversionConstant), constant); 
    } 
} 

下面的語句應該返回完全相同的值fileInfo.Length,但由於1024^0不返回1,它顯示的是千字節數。請注意,我在一行中都使用了GetValueFromBytes方法,但是我將它分開以查看可能導致錯誤計算的原因。

UnitConversion.GetValueFromBytes(fileInfo.Length, 
           UnitConversion.ByteConversionConstant.B) 

我不知道這是否是與鑄造enumint或者如果有什麼問題引發一個int時的int並將其分配給一個long丟失,但是這是奇怪的行爲。

回答

15

您使用the ^ operator,這是乘方運算符。它是「異或」的。

使用Math.Pow用於冪 - 或更好,只是用在這種情況下位移位:

long divided = bytes >> (n * 10); 
return divided.ToString() + ...; 

或者,你可以改變你的枚舉值和實際值的劃分:

public enum ByteConversionConstant : long 
{ 
    B = 1L << 0, 
    KB = 1L << 10, 
    MB = 1L << 20, 
    GB = 1L << 30, 
    TB = 1L << 40, 
    PB = 1L << 50 
} 

Then:

long divided = n/(long) constant; 
+0

感謝您指出這一點。我不確定我是如何混淆了'Math.Pow'和按位操作符'^'。 –

7

^XOR運營商。你想通過Math.Pow完成。

+2

那麼我們得到了Skeet'd。 –

+0

@Pierre:哈哈的確如此。 –

+1

+1,因爲你們先回答了 – AlexDev

6

^是一個按位運算符,您目前正在執行'1024 XOR 0'。

我認爲你正在尋找Math.Pow(1024, n);,這是「1024冪0」

3

^ operator doe s不會將這個數字提高到這個數字,它就是Bitwise XOR運營商。

你想Math.Pow

long divisor = Math.Pow(1024, n);