क्या .NET, KB, MB, GB आदि को बाइट्स को बदलने का एक आसान तरीका प्रदान करता है?


112

अगर .NET ऐसा करने के लिए एक साफ तरीका प्रदान करता है तो बस सोच रहा हूँ:

int64 x = 1000000;
string y = null;
if (x / 1024 == 0) {
    y = x + " bytes";
}
else if (x / (1024 * 1024) == 0) {
    y = string.Format("{0:n1} KB", x / 1024f);
}

आदि...

जवाबों:


193

यहाँ यह करने के लिए एक काफी संक्षिप्त तरीका है:

static readonly string[] SizeSuffixes = 
                   { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (decimalPlaces < 0) { throw new ArgumentOutOfRangeException("decimalPlaces"); }
    if (value < 0) { return "-" + SizeSuffix(-value); } 
    if (value == 0) { return string.Format("{0:n" + decimalPlaces + "} bytes", 0); }

    // mag is 0 for bytes, 1 for KB, 2, for MB, etc.
    int mag = (int)Math.Log(value, 1024);

    // 1L << (mag * 10) == 2 ^ (10 * mag) 
    // [i.e. the number of bytes in the unit corresponding to mag]
    decimal adjustedSize = (decimal)value / (1L << (mag * 10));

    // make adjustment when the value is large enough that
    // it would round up to 1000 or more
    if (Math.Round(adjustedSize, decimalPlaces) >= 1000)
    {
        mag += 1;
        adjustedSize /= 1024;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", 
        adjustedSize, 
        SizeSuffixes[mag]);
}

और यहाँ मूल कार्यान्वयन मैंने सुझाया है, जो थोड़ा धीमा हो सकता है, लेकिन इसका पालन करना थोड़ा आसान है:

static readonly string[] SizeSuffixes = 
                  { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

static string SizeSuffix(Int64 value, int decimalPlaces = 1)
{
    if (value < 0) { return "-" + SizeSuffix(-value); } 

    int i = 0;
    decimal dValue = (decimal)value;
    while (Math.Round(dValue, decimalPlaces) >= 1000)
    {
        dValue /= 1024;
        i++;
    }

    return string.Format("{0:n" + decimalPlaces + "} {1}", dValue, SizeSuffixes[i]);
}

Console.WriteLine(SizeSuffix(100005000L));

एक बात ध्यान में रखना - SI संकेतन में, "किलो" आमतौर पर एक लोअरकेस k का उपयोग करता है जबकि सभी बड़ी इकाइयाँ एक बड़े अक्षर का उपयोग करती हैं। Windows KB, MB, GB का उपयोग करता है, इसलिए मैंने ऊपर KB का उपयोग किया है, लेकिन आप इसके बजाय kB पर विचार कर सकते हैं।


पूछने वाला केवल सटीकता के 1 दशमलव स्थान की तलाश में है। क्या आप एक ऐसे इनपुट का उदाहरण दे सकते हैं जो गलत आउटपुट देता है?
20

2
दोनों उदाहरण अब फ्लोटिंग पॉइंट डिवीजन का उपयोग करते हैं इसलिए राउंडिंग त्रुटियों के बारे में बहुत कम चिंता होनी चाहिए।
JLRishe

धन्यवाद, बस मैं जो चाह रहा था। (दूसरा कार्यान्वयन।)
स्नैप्लेक्स

1
बहुत साफ-सुथरा कार्यान्वयन। ध्यान दें कि यदि आप इस फ़ंक्शन को मान 0 देते हैं, तो यह IndexOutOfRangeException को फेंक देगा। मैंने if (value == 0) { return "0"; }फ़ंक्शन के अंदर एक चेक जोड़ने का फैसला किया ।
15

क्या आप मामला प्रदान कर सकते हैं जब फ़ाइल का आकार <0 है? मेरे लिए यह अजीब लगता है ...
रुस्लान एफ

85

चेकआउट बाइट्स लाइब्रेरी। यह System.TimeSpanबाइट्स के लिए है!

यह आपके लिए रूपांतरण और स्वरूपण को संभालता है।

var maxFileSize = ByteSize.FromKiloBytes(10);
maxFileSize.Bytes;
maxFileSize.MegaBytes;
maxFileSize.GigaBytes;

यह स्ट्रिंग प्रतिनिधित्व और पार्सिंग भी करता है।

// ToString
ByteSize.FromKiloBytes(1024).ToString(); // 1 MB
ByteSize.FromGigabytes(.5).ToString();   // 512 MB
ByteSize.FromGigabytes(1024).ToString(); // 1 TB

// Parsing
ByteSize.Parse("5b");
ByteSize.Parse("1.55B");

6
उपयोग करने और समझने में सरल, और यह .Net 4.0 और ऊपर के साथ काम करता है।
जोकर

34
इसे .NET फ्रेमवर्क के भाग के रूप में शामिल किया जाना चाहिए
helios456

मेरी एकमात्र समस्या यह है कि रूपांतरण विधियाँ केवल गैर-बाइट से बाइट तक काम करती हैं, लेकिन कोई अन्य तरीका नहीं है।
सुपर जेएमएन

@SuperJMN का क्या मतलब है गैर-बाइट? बिट्स की तरह? एक .FromBits विधि है जिसका आप उपयोग कर सकते हैं।
उमर

1
यदि आपका स्रोत डेटा "बाइट्स" के अलावा कुछ है और आपको कुछ भी बदलने में सक्षम होने की आवश्यकता है ... यह वह लाइब्रेरी है जिसका आपको उपयोग करना चाहिए।
जेम्स ब्लेक

38

चूंकि हर कोई अपने तरीकों को पोस्ट कर रहा है, मुझे लगा कि मैं इसके लिए आमतौर पर उपयोग की जाने वाली विस्तार विधि पोस्ट करूंगा:

संपादित करें: इंट / लंबे वेरिएंट जोड़े गए ... और एक कोपिस्टा टाइपो तय किया ...

public static class Ext
{
    private const long OneKb = 1024;
    private const long OneMb = OneKb * 1024;
    private const long OneGb = OneMb * 1024;
    private const long OneTb = OneGb * 1024;

    public static string ToPrettySize(this int value, int decimalPlaces = 0)
    {
        return ((long)value).ToPrettySize(decimalPlaces);
    }

    public static string ToPrettySize(this long value, int decimalPlaces = 0)
    {
        var asTb = Math.Round((double)value / OneTb, decimalPlaces);
        var asGb = Math.Round((double)value / OneGb, decimalPlaces);
        var asMb = Math.Round((double)value / OneMb, decimalPlaces);
        var asKb = Math.Round((double)value / OneKb, decimalPlaces);
        string chosenValue = asTb > 1 ? string.Format("{0}Tb",asTb)
            : asGb > 1 ? string.Format("{0}Gb",asGb)
            : asMb > 1 ? string.Format("{0}Mb",asMb)
            : asKb > 1 ? string.Format("{0}Kb",asKb)
            : string.Format("{0}B", Math.Round((double)value, decimalPlaces));
        return chosenValue;
    }
}

हालांकि यह ध्यान रखें कि लोअरकेस b आमतौर पर बाइट्स के बजाय बिट्स को दर्शाता है। :-) en.wikipedia.org/wiki/Data-rate_units#Kilobit_per_second
शार्प

32

मैं इसका उपयोग करके इसे हल करूंगा Extension methods, Math.Powफ़ंक्शन और Enums:

public static class MyExtension
{
    public enum SizeUnits
    {
        Byte, KB, MB, GB, TB, PB, EB, ZB, YB
    }

    public static string ToSize(this Int64 value, SizeUnits unit)
    {
        return (value / (double)Math.Pow(1024, (Int64)unit)).ToString("0.00");
    }
}

और इसका उपयोग करें:

string h = x.ToSize(MyExtension.SizeUnits.KB);

3
सुरुचिपूर्ण समाधान!
योसिको

1
मैंने आपके विचार का उपयोग एक बनाने के लिए किया है जो स्वचालित रूप से इकाई निर्धारित करता है। +1
लुइस सोमर

2
यह एक बहुत ही सुंदर समाधान है, जो बहुत साफ है और स्वीकृत समाधान है। हालाँकि, एनम मूल्यों के आधार पर कड़ाई से यह 1000 की शक्ति पर आधारित होना चाहिए, अर्थात 1024 नहीं ( en.wikipedia.org/wiki/Terabyte ) कोड ... सार्वजनिक स्थैतिक स्ट्रिंग ToSize (यह लंबा मान, इकाई इकाई) => $ "{मान / गणित. पाव (1000, (लंबी) इकाई): F2} {यूनिट.टॉस्ट्रिंग ()}";
स्टोज

6

सबसे अधिक वोट किए गए उत्तर के लघु संस्करण में टीबी मूल्यों के साथ समस्याएं हैं।

मैंने इसे उचित रूप से tb मानों को संभालने के लिए उचित रूप से समायोजित किया और फिर भी एक लूप के बिना और नकारात्मक मानों के लिए थोड़ी सी त्रुटि जाँच को भी जोड़ा। यहाँ मेरा समाधान है:

static readonly string[] SizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
static string SizeSuffix(long value, int decimalPlaces = 0)
{
    if (value < 0)
    {
        throw new ArgumentException("Bytes should not be negative", "value");
    }
    var mag = (int)Math.Max(0, Math.Log(value, 1024));
    var adjustedSize = Math.Round(value / Math.Pow(1024, mag), decimalPlaces);
    return String.Format("{0} {1}", adjustedSize, SizeSuffixes[mag]);
}

1
बड़े मूल्यों के साथ कहा गया मुद्दा अब स्वीकृत उत्तर में मौजूद नहीं होना चाहिए।
JLRishe

5

नहीं, ज्यादातर इसलिए क्योंकि यह एक आला जगह की जरूरत है, और वहाँ भी कई संभावित रूपांतर हैं। (क्या यह "KB", "Kb" या "Ko" है? एक मेगाबाइट 1024 * 1024 बाइट्स, या 1024 या 1000 बाइट्स? - हाँ, कुछ जगहों पर इसका उपयोग होता है!)


1
+1 - विकिपीडिया के अनुसार , kb => 1000 बाइट्स, और KiB => 1024 बाइट्स।
पीटर मजीद

5

यहां एक ऐसा विकल्प है जो आपकी तुलना में विस्तार करना आसान है, लेकिन नहीं, पुस्तकालय में कोई भी निर्मित नहीं है।

private static List<string> suffixes = new List<string> { " B", " KB", " MB", " GB", " TB", " PB" };
public static string Foo(int number)
{
    for (int i = 0; i < suffixes.Count; i++)
    {
        int temp = number / (int)Math.Pow(1024, i + 1);
        if (temp == 0)
            return (number / (int)Math.Pow(1024, i)) + suffixes[i];
    }
    return number.ToString();
}

4
    private string GetFileSize(double byteCount)
    {
        string size = "0 Bytes";
        if (byteCount >= 1073741824.0)
            size = String.Format("{0:##.##}", byteCount / 1073741824.0) + " GB";
        else if (byteCount >= 1048576.0)
            size = String.Format("{0:##.##}", byteCount / 1048576.0) + " MB";
        else if (byteCount >= 1024.0)
            size = String.Format("{0:##.##}", byteCount / 1024.0) + " KB";
        else if (byteCount > 0 && byteCount < 1024.0)
            size = byteCount.ToString() + " Bytes";

        return size;
    }

    private void btnBrowse_Click(object sender, EventArgs e)
    {
        if (openFile1.ShowDialog() == DialogResult.OK)
        {
            FileInfo thisFile = new FileInfo(openFile1.FileName);

            string info = "";

            info += "File: " + Path.GetFileName(openFile1.FileName);
            info += Environment.NewLine;
            info += "File Size: " + GetFileSize((int)thisFile.Length);

            label1.Text = info;
        }
    }

यह इसे अस्वस्थ करने का एक तरीका है (संख्या 1073741824.0 1024 * 1024 * 1024 उर्फ ​​जीबी से है)


3

@ सर्व का जवाब अच्छा और सक्सेसफुल था। मुझे लगता है कि यह और भी सरल हो सकता है?

private static string[] suffixes = new [] { " B", " KB", " MB", " GB", " TB", " PB" };

public static string ToSize(double number, int precision = 2)
{
    // unit's number of bytes
    const double unit = 1024;
    // suffix counter
    int i = 0;
    // as long as we're bigger than a unit, keep going
    while(number > unit)
    {
        number /= unit;
        i++;
    }
    // apply precision and current suffix
    return Math.Round(number, precision) + suffixes[i];
}

3

NeverHopeless के सुरुचिपूर्ण समाधान पर आधारित:

private static readonly KeyValuePair<long, string>[] Thresholds = 
{
    // new KeyValuePair<long, string>(0, " Bytes"), // Don't devide by Zero!
    new KeyValuePair<long, string>(1, " Byte"),
    new KeyValuePair<long, string>(2, " Bytes"),
    new KeyValuePair<long, string>(1024, " KB"),
    new KeyValuePair<long, string>(1048576, " MB"), // Note: 1024 ^ 2 = 1026 (xor operator)
    new KeyValuePair<long, string>(1073741824, " GB"),
    new KeyValuePair<long, string>(1099511627776, " TB"),
    new KeyValuePair<long, string>(1125899906842620, " PB"),
    new KeyValuePair<long, string>(1152921504606850000, " EB"),

    // These don't fit into a int64
    // new KeyValuePair<long, string>(1180591620717410000000, " ZB"), 
    // new KeyValuePair<long, string>(1208925819614630000000000, " YB") 
};

/// <summary>
/// Returns x Bytes, kB, Mb, etc... 
/// </summary>
public static string ToByteSize(this long value)
{
    if (value == 0) return "0 Bytes"; // zero is plural
    for (int t = Thresholds.Length - 1; t > 0; t--)
        if (value >= Thresholds[t].Key) return ((double)value / Thresholds[t].Key).ToString("0.00") + Thresholds[t].Value;
    return "-" + ToByteSize(-value); // negative bytes (common case optimised to the end of this routine)
}

हो सकता है कि अत्यधिक टिप्पणियां हों, लेकिन मैं भविष्य की यात्राओं पर खुद को वही गलतियां करने से रोकने के लिए उन्हें छोड़ देता हूं ...


2

नहीं।

लेकिन आप इस तरह से लागू कर सकते हैं;

    static double ConvertBytesToMegabytes(long bytes)
    {
    return (bytes / 1024f) / 1024f;
    }

    static double ConvertKilobytesToMegabytes(long kilobytes)
    {
    return kilobytes / 1024f;
    }

यह भी देखें कि बाइट्स को मेगा या गीगाबाइट में फाइलों को सही ढंग से कैसे बदलें?


1

मैंने यहां कुछ उत्तरों को दो तरीकों से संयोजित किया है जो कि बहुत अच्छे हैं। नीचे दी गई दूसरी विधि एक बाइट्स स्ट्रिंग (1.5.1 जीबी की तरह) से बाइट्स (जैसे 1621350140) को लंबे प्रकार के मान के रूप में परिवर्तित करेगी। मुझे आशा है कि यह बाइट्स को स्ट्रिंग में बदलने और बाइट्स में वापस खोजने के समाधान की तलाश में दूसरों के लिए उपयोगी है।

public static string BytesAsString(float bytes)
{
    string[] suffix = { "B", "KB", "MB", "GB", "TB" };
    int i;
    double doubleBytes = 0;

    for (i = 0; (int)(bytes / 1024) > 0; i++, bytes /= 1024)
    {
        doubleBytes = bytes / 1024.0;
    }

    return string.Format("{0:0.00} {1}", doubleBytes, suffix[i]);
}

public static long StringAsBytes(string bytesString)
{
    if (string.IsNullOrEmpty(bytesString))
    {
        return 0;
    }

    const long OneKb = 1024;
    const long OneMb = OneKb * 1024;
    const long OneGb = OneMb * 1024;
    const long OneTb = OneGb * 1024;
    double returnValue;
    string suffix = string.Empty;

    if (bytesString.IndexOf(" ") > 0)
    {
        returnValue = float.Parse(bytesString.Substring(0, bytesString.IndexOf(" ")));
        suffix = bytesString.Substring(bytesString.IndexOf(" ") + 1).ToUpperInvariant();
    }
    else
    {
        returnValue = float.Parse(bytesString.Substring(0, bytesString.Length - 2));
        suffix = bytesString.ToUpperInvariant().Substring(bytesString.Length - 2);
    }

    switch (suffix)
    {
        case "KB":
            {
                returnValue *= OneKb;
                break;
            }

        case "MB":
            {
                returnValue *= OneMb;
                break;
            }

        case "GB":
            {
                returnValue *= OneGb;
                break;
            }

        case "TB":
            {
                returnValue *= OneTb;
                break;
            }

        default:
            {
                break;
            }
    }

    return Convert.ToInt64(returnValue);
}

मैं पूछ सकता क्यों आप का उपयोग float.Parseकरने के लिए double?
जॉन_ज

1

मुझे पता है कि यह पुराना धागा पहले से ही है। लेकिन शायद कोई समाधान खोजेगा। और यहाँ मैं क्या उपयोग करता हूं और सबसे आसान तरीका है

  public static string FormatFileSize(long bytes) 
    {
        var unit = 1024;
        if (bytes < unit)
        {
            return $"{bytes} B";
        }
        var exp = (int)(Math.Log(bytes) / Math.Log(unit));
        return $"{bytes / Math.Pow(unit, exp):F2} " +
               $"{("KMGTPE")[exp - 1]}B";
    }

0

कैसा रहेगा:

public void printMB(uint sizekB)   
{
    double sizeMB = (double) sizekB / 1024;
    Console.WriteLine("Size is " + sizeMB.ToString("0.00") + "MB");
}

जैसे कॉल करना

printMB(123456);

परिणाम में उत्पादन होगा

"Size is 120,56 MB"

0

मैं JerKimballs समाधान के लिए गया था, और उस तक अंगूठे। हालाँकि, मैं यह जोड़ना / बताना चाहूंगा कि यह वास्तव में समग्र रूप से विवाद का विषय है। अपने शोध में (अन्य कारणों से) मैं निम्नलिखित जानकारी के साथ आया हूं।

जब सामान्य लोग (मैंने सुना है कि वे मौजूद हैं) गीगाबाइट की बात करते हैं, तो वे मीट्रिक प्रणाली को संदर्भित करते हैं जिसमें 1000 से 3 बाइट्स की मूल संख्या == गीगाबाइट की संख्या से होती है। हालाँकि, निश्चित रूप से IEC / JEDEC मानक हैं, जो विकिपीडिया में अच्छी तरह से अभिव्यक्त किए गए हैं, जो कि x की शक्ति के 1000 के बजाय उनके 1024 हैं। जो भौतिक भंडारण उपकरणों के लिए है (और मुझे लगता है जैसे कि amazon और अन्य जैसे तार्किक हैं) मीट्रिक बनाम IEC के बीच बढ़ते अंतर। उदाहरण के लिए 1 टीबी == 1 टेराबाइट मीट्रिक 4 की शक्ति के लिए 1000 है, लेकिन आईईसी आधिकारिक तौर पर 1 टीआईबी के समान संख्या, टीबीबाइट को 1024 की शक्ति के बराबर है। 4. लेकिन, अफसोस, गैर-तकनीकी अनुप्रयोगों में (मैं) दर्शकों द्वारा जाना) मानक मीट्रिक है, और आंतरिक उपयोग के लिए मेरे अपने ऐप में वर्तमान में मैं प्रलेखन में अंतर समझाता हूं। लेकिन प्रदर्शन के उद्देश्य से मैं कुछ भी नहीं बल्कि मीट्रिक प्रदान करता हूं। आंतरिक रूप से भले ही यह मेरे ऐप में प्रासंगिक नहीं है लेकिन मैं केवल बाइट्स स्टोर करता हूं और प्रदर्शन के लिए गणना करता हूं।

एक साइड नोट के रूप में मुझे कुछ हद तक यह पता चलता है कि नेट फ्रेमवर्क AFAIK (और मैं अक्सर गलत है कि शक्तियों का शुक्रिया अदा करता हूं) यहां तक ​​कि 4.5 अवतार में आंतरिक रूप से किसी भी लाइब्रेरी में इसके बारे में कुछ भी शामिल नहीं है। किसी को किसी तरह के ओपन सोर्स लाइब्रेरी की उम्मीद होगी, जो किसी समय नूजीटेबल हो, लेकिन मैं मानता हूं कि यह एक छोटा सा पेशाब है। दूसरी ओर System.IO.DriveInfo और अन्य लोगों के पास भी केवल बाइट्स (लंबे समय तक) हैं, जो स्पष्ट है।


0
public static class MyExtension
{
    public static string ToPrettySize(this float Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    public static string ToPrettySize(this int Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    private static string ConvertToPrettySize(float Size, int R)
    {
        float F = Size / 1024f;
        if (F < 1)
        {
            switch (R)
            {
                case 0:
                    return string.Format("{0:0.00} byte", Size);
                case 1:
                    return string.Format("{0:0.00} kb", Size);
                case 2:
                    return string.Format("{0:0.00} mb", Size);
                case 3:
                    return string.Format("{0:0.00} gb", Size);
            }
        }
        return ConvertToPrettySize(F, ++R);
    }
}

0

कुछ पुनरावृत्ति के बारे में कैसे:

private static string ReturnSize(double size, string sizeLabel)
{
  if (size > 1024)
  {
    if (sizeLabel.Length == 0)
      return ReturnSize(size / 1024, "KB");
    else if (sizeLabel == "KB")
      return ReturnSize(size / 1024, "MB");
    else if (sizeLabel == "MB")
      return ReturnSize(size / 1024, "GB");
    else if (sizeLabel == "GB")
      return ReturnSize(size / 1024, "TB");
    else
      return ReturnSize(size / 1024, "PB");
  }
  else
  {
    if (sizeLabel.Length > 0)
      return string.Concat(size.ToString("0.00"), sizeLabel);
    else
      return string.Concat(size.ToString("0.00"), "Bytes");
  }
}

तब आप इसे कॉल कर सकते हैं:

ReturnSize(size, string.Empty);

0

जैसा कि ऊपर पोस्ट किया गया है, पुनरावृत्ति पसंदीदा तरीका है, लघुगणक की मदद से।

निम्नलिखित फ़ंक्शन के 3 तर्क हैं: इनपुट, आउटपुट का आयाम बाधा, यह तीसरा तर्क है।

int ByteReDim(unsigned long ival, int constraint, unsigned long *oval)
{
    int base = 1 + (int) log10(ival);

    (*oval) = ival;
    if (base > constraint) {
        (*oval) = (*oval) >> 10;
        return(1 + ByteReDim((*oval), constraint, oval));
    } else
        return(0);
}

अब 12GB RAM को कई इकाइयों में परिवर्तित करते हैं:

int main(void)
{
    unsigned long RAM;
    int unit; // index of below symbols array
    char symbol[5] = {'B', 'K', 'M', 'G', 'T'};

    unit = ByteReDim(12884901888, 12, &RAM);
    printf("%lu%c\n", RAM, symbol[unit]); // output is 12884901888B

    unit = ByteReDim(12884901888, 9, &RAM);
    printf("%lu%c\n", RAM, symbol[unit]); // output is 12582912K

    unit = ByteReDim(12884901888, 6, &RAM);
    printf("%lu%c\n", RAM, symbol[unit]); // output is 12288M

    unit = ByteReDim(12884901888, 3, &RAM);
    printf("%lu%c\n", RAM, symbol[unit]); // output is 12G
}

0

मैं इसका उपयोग विंडोज (बाइनरी प्रीफिक्स) के लिए करता हूं:

static readonly string[] BinaryPrefix = { "bytes", "KB", "MB", "GB", "TB" }; // , "PB", "EB", "ZB", "YB"
string GetMemoryString(double bytes)
{
    int counter = 0;
    double value = bytes;
    string text = "";
    do
    {
        text = value.ToString("0.0") + " " + BinaryPrefix[counter];
        value /= 1024;
        counter++;
    }
    while (Math.Floor(value) > 0 && counter < BinaryPrefix.Length);
    return text;
}

0

मैंने इसे अपनी परियोजना के लिए एक UWP डेटाबाइंडिंग कनवर्टर में (थोड़ा से कोई संशोधन के साथ) शामिल किया है और सोचा कि यह दूसरों के लिए भी उपयोगी हो सकता है।

कोड है:

using System;
using System.Text;
using Windows.UI.Xaml.Data;

namespace MyApp.Converters
{
    public class ByteSizeConverter : IValueConverter
    {
        static readonly string[] sSizeSuffixes = { "bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };

        // The number of decimal places the formatter should include in the scaled output - default 1dp
        public int DecimalPlaces { get; set; } = 1;

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            Int64 intVal = System.Convert.ToInt64(value);

            return SizeSuffix(intVal);
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            // TODO: Parse string into number and suffix
            //       Scale number by suffix multiplier to get bytes
            throw new NotImplementedException();
        }

        string SizeSuffix(Int64 value)
        {
            if (this.DecimalPlaces < 0) { throw new ArgumentOutOfRangeException(String.Format("DecimalPlaces = {0}", this.DecimalPlaces)); }
            if (value < 0) { return "-" + SizeSuffix(-value); }
            if (value == 0) { return string.Format("{0:n" + this.DecimalPlaces + "} bytes", 0); }

            // magnitude is 0 for bytes, 1 for KB, 2, for MB, etc.
            int magnitude = (int)Math.Log(value, 1024);
            // clip magnitude - only 8 values currently supported, this prevents out-of-bounds exception
            magnitude = Math.Min(magnitude, 8);

            // 1L << (magnitude * 10) == 2 ^ (10 * magnitude) [i.e. the number of bytes in the unit corresponding to magnitude]
            decimal adjustedSize = (decimal)value / (1L << (magnitude * 10));

            // make adjustment when the value is large enough that it would round up to 1000 or more
            if (Math.Round(adjustedSize, this.DecimalPlaces) >= 1000)
            {
                magnitude += 1;
                adjustedSize /= 1024;
            }

            return String.Format("{0:n" + this.DecimalPlaces + "} {1}", adjustedSize, sSizeSuffixes[magnitude]);
        }
    }
}

इसका उपयोग करने के लिए, अपने UserControl या पेज XAML में एक स्थानीय संसाधन जोड़ें:

<UserControl.Resources>
    <converters:ByteSizeConverter x:Key="ByteFormat" DecimalPlaces="3" />
</UserControl.Resources>

इसे डेटा बाइंडिंग टेम्प्लेट या डेटा बाइंडिंग इंस्टेंस में देखें:

<TextBlock HorizontalAlignment="Left" VerticalAlignment="Center"
    Text="{x:Bind MyItem.FileSize_bytes, Mode=OneWay, Converter={StaticResource ByteFormat}}" />

और हे प्रिस्टो। जादू होता है।


0

https://github.com/logary/logary/blob/master/src/Logary/DataModel.fs#L832-L837

let scaleBytes (value : float) : float * string =
    let log2 x = log x / log 2.
    let prefixes = [| ""; "Ki"; "Mi"; "Gi"; "Ti"; "Pi" |] // note the capital K and the 'i'
    let index = int (log2 value) / 10
    1. / 2.**(float index * 10.),
sprintf "%s%s" prefixes.[index] (Units.symbol Bytes)

(अस्वीकरण: मैंने यह कोड, लिंक में भी कोड लिखा है!)

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.