जवाबों:
यहाँ यह करने के लिए एक काफी संक्षिप्त तरीका है:
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 पर विचार कर सकते हैं।
if (value == 0) { return "0"; }
फ़ंक्शन के अंदर एक चेक जोड़ने का फैसला किया ।
चेकआउट बाइट्स लाइब्रेरी। यह 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");
चूंकि हर कोई अपने तरीकों को पोस्ट कर रहा है, मुझे लगा कि मैं इसके लिए आमतौर पर उपयोग की जाने वाली विस्तार विधि पोस्ट करूंगा:
संपादित करें: इंट / लंबे वेरिएंट जोड़े गए ... और एक कोपिस्टा टाइपो तय किया ...
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;
}
}
मैं इसका उपयोग करके इसे हल करूंगा 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);
सबसे अधिक वोट किए गए उत्तर के लघु संस्करण में टीबी मूल्यों के साथ समस्याएं हैं।
मैंने इसे उचित रूप से 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]);
}
नहीं, ज्यादातर इसलिए क्योंकि यह एक आला जगह की जरूरत है, और वहाँ भी कई संभावित रूपांतर हैं। (क्या यह "KB", "Kb" या "Ko" है? एक मेगाबाइट 1024 * 1024 बाइट्स, या 1024 या 1000 बाइट्स? - हाँ, कुछ जगहों पर इसका उपयोग होता है!)
यहां एक ऐसा विकल्प है जो आपकी तुलना में विस्तार करना आसान है, लेकिन नहीं, पुस्तकालय में कोई भी निर्मित नहीं है।
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();
}
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 उर्फ जीबी से है)
@ सर्व का जवाब अच्छा और सक्सेसफुल था। मुझे लगता है कि यह और भी सरल हो सकता है?
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];
}
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)
}
हो सकता है कि अत्यधिक टिप्पणियां हों, लेकिन मैं भविष्य की यात्राओं पर खुद को वही गलतियां करने से रोकने के लिए उन्हें छोड़ देता हूं ...
नहीं।
लेकिन आप इस तरह से लागू कर सकते हैं;
static double ConvertBytesToMegabytes(long bytes)
{
return (bytes / 1024f) / 1024f;
}
static double ConvertKilobytesToMegabytes(long kilobytes)
{
return kilobytes / 1024f;
}
यह भी देखें कि बाइट्स को मेगा या गीगाबाइट में फाइलों को सही ढंग से कैसे बदलें?
मैंने यहां कुछ उत्तरों को दो तरीकों से संयोजित किया है जो कि बहुत अच्छे हैं। नीचे दी गई दूसरी विधि एक बाइट्स स्ट्रिंग (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
?
मुझे पता है कि यह पुराना धागा पहले से ही है। लेकिन शायद कोई समाधान खोजेगा। और यहाँ मैं क्या उपयोग करता हूं और सबसे आसान तरीका है
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";
}
मैं JerKimballs समाधान के लिए गया था, और उस तक अंगूठे। हालाँकि, मैं यह जोड़ना / बताना चाहूंगा कि यह वास्तव में समग्र रूप से विवाद का विषय है। अपने शोध में (अन्य कारणों से) मैं निम्नलिखित जानकारी के साथ आया हूं।
जब सामान्य लोग (मैंने सुना है कि वे मौजूद हैं) गीगाबाइट की बात करते हैं, तो वे मीट्रिक प्रणाली को संदर्भित करते हैं जिसमें 1000 से 3 बाइट्स की मूल संख्या == गीगाबाइट की संख्या से होती है। हालाँकि, निश्चित रूप से IEC / JEDEC मानक हैं, जो विकिपीडिया में अच्छी तरह से अभिव्यक्त किए गए हैं, जो कि x की शक्ति के 1000 के बजाय उनके 1024 हैं। जो भौतिक भंडारण उपकरणों के लिए है (और मुझे लगता है जैसे कि amazon और अन्य जैसे तार्किक हैं) मीट्रिक बनाम IEC के बीच बढ़ते अंतर। उदाहरण के लिए 1 टीबी == 1 टेराबाइट मीट्रिक 4 की शक्ति के लिए 1000 है, लेकिन आईईसी आधिकारिक तौर पर 1 टीआईबी के समान संख्या, टीबीबाइट को 1024 की शक्ति के बराबर है। 4. लेकिन, अफसोस, गैर-तकनीकी अनुप्रयोगों में (मैं) दर्शकों द्वारा जाना) मानक मीट्रिक है, और आंतरिक उपयोग के लिए मेरे अपने ऐप में वर्तमान में मैं प्रलेखन में अंतर समझाता हूं। लेकिन प्रदर्शन के उद्देश्य से मैं कुछ भी नहीं बल्कि मीट्रिक प्रदान करता हूं। आंतरिक रूप से भले ही यह मेरे ऐप में प्रासंगिक नहीं है लेकिन मैं केवल बाइट्स स्टोर करता हूं और प्रदर्शन के लिए गणना करता हूं।
एक साइड नोट के रूप में मुझे कुछ हद तक यह पता चलता है कि नेट फ्रेमवर्क AFAIK (और मैं अक्सर गलत है कि शक्तियों का शुक्रिया अदा करता हूं) यहां तक कि 4.5 अवतार में आंतरिक रूप से किसी भी लाइब्रेरी में इसके बारे में कुछ भी शामिल नहीं है। किसी को किसी तरह के ओपन सोर्स लाइब्रेरी की उम्मीद होगी, जो किसी समय नूजीटेबल हो, लेकिन मैं मानता हूं कि यह एक छोटा सा पेशाब है। दूसरी ओर System.IO.DriveInfo और अन्य लोगों के पास भी केवल बाइट्स (लंबे समय तक) हैं, जो स्पष्ट है।
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);
}
}
कुछ पुनरावृत्ति के बारे में कैसे:
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);
जैसा कि ऊपर पोस्ट किया गया है, पुनरावृत्ति पसंदीदा तरीका है, लघुगणक की मदद से।
निम्नलिखित फ़ंक्शन के 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
}
मैं इसका उपयोग विंडोज (बाइनरी प्रीफिक्स) के लिए करता हूं:
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;
}
मैंने इसे अपनी परियोजना के लिए एक 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}}" />
और हे प्रिस्टो। जादू होता है।
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)
(अस्वीकरण: मैंने यह कोड, लिंक में भी कोड लिखा है!)