উত্তর:
এটি করার জন্য এখানে মোটামুটি সংক্ষিপ্ত উপায়:
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));
একটি বিষয় মনে রাখবেন - এসআই স্বরলিপিতে, "কিলো" সাধারণত লোয়ারকেস কে ব্যবহার করে তবে বৃহত্তর ইউনিটগুলির সমস্ত একটি মূলধন অক্ষর ব্যবহার করে। উইন্ডোজ কেবি, এমবি, জিবি ব্যবহার করে, তাই আমি উপরের কেবি ব্যবহার করেছি তবে আপনি তার পরিবর্তে কেবি বিবেচনা করতে পারেন।
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);
সর্বাধিক ভোট দেওয়া উত্তরের সংক্ষিপ্ত সংস্করণে টিবি মানগুলির সাথে সমস্যা রয়েছে।
আমি টিবি মানগুলি হ্যান্ডেল করার জন্য এটি যথাযথভাবে সামঞ্জস্য করেছি এবং এখনও একটি লুপ ছাড়াই এবং নেতিবাচক মানগুলি পরীক্ষা করার জন্য কিছুটা ত্রুটি যুক্ত করেছি। আমার সমাধানটি এখানে:
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]);
}
না। বেশিরভাগ কারণ এটি একেবারে কুলুঙ্গিক প্রয়োজন, এবং এর সম্ভাব্য বিভিন্নতা রয়েছে। (এটি কি "কেবি", "কেবি" বা "কো"? একটি মেগাবাইট 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];
}
নেভারহোপলেস এর মার্জিত সমাধানের ভিত্তিতে:
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";
}
আমি জেরকিমবলস সলিউশনের জন্য গিয়েছিলাম, এবং থাম্বস অবধি। যাইহোক, আমি যোগ / উল্লেখ করতে চাই যে এটি সত্যই সামগ্রিকভাবে বিতর্কের বিষয়। আমার গবেষণায় (অন্যান্য কারণে) আমি নিম্নলিখিত তথ্যগুলির টুকরো নিয়ে এসেছি।
যখন সাধারণ লোকেরা (আমি শুনেছি তারা বিদ্যমান আছে) গিগাবাইটের কথা বলে তারা মেট্রিক পদ্ধতিতে উল্লেখ করে যেখানে 1000 এর বাইটের আসল সংখ্যা থেকে = = গিগাবাইটের সংখ্যা। তবে, অবশ্যই উইকিপিডিয়ায় আইইসি / জেইডইসি স্ট্যান্ডার্ড রয়েছে যা সঠিকভাবে সংক্ষিপ্তভাবে উইকিপিডিয়ায় সংক্ষিপ্তভাবে তৈরি করা হয়েছে, যা তাদের পরিবর্তে ১০০ টি এক্স এর ক্ষমতার পরিবর্তে ১০৪৪ টি। যা শারীরিক স্টোরেজ ডিভাইসের জন্য (এবং আমি যেমন অ্যামাজন এবং অন্যান্যদের মতো যৌক্তিক অনুমান করি) এর অর্থ একটি মেট্রিক বনাম আইইসি মধ্যে বর্ধমান পার্থক্য difference উদাহরণস্বরূপ, 1 টিবি == 1 টেরাবাইট মেট্রিক 4 পাওয়ার ক্ষমতার 1000, তবে আইইসি আনুষ্ঠানিকভাবে 1 টিআইবি হিসাবে একই সংখ্যাকে, 1024 হিসাবে 4 পাওয়ার সাফল্য হিসাবে বোঝায় তবে হায়, হতাশায়, প্রযুক্তিগত অ্যাপ্লিকেশনগুলিতে (আমি চাই শ্রোতার দ্বারা যান) আদর্শটি মেট্রিক, এবং অভ্যন্তরীণ ব্যবহারের জন্য আমার নিজের অ্যাপে বর্তমানে আমি ডকুমেন্টেশনের পার্থক্যটি ব্যাখ্যা করি। তবে প্রদর্শনের উদ্দেশ্যে আমি মেট্রিক ছাড়াও আর কিছু দিই না। অভ্যন্তরীণভাবে এটি আমার অ্যাপে প্রাসঙ্গিক না হলেও আমি কেবল বাইট সঞ্চয় করি এবং প্রদর্শনের জন্য গণনা করি।
পার্শ্ব নোট হিসাবে আমি এটি কিছুটা অপ্রতিরোধ্য বলে মনে করি যে নেট ফ্রেমওয়ার্ক AFAIK (এবং আমি প্রায়শই ভুল হতে পারি যে শক্তিগুলি ধন্যবাদ জানায়) এমনকি এর 4.5.৪ অবতারের অভ্যন্তরীণ কোনও লাইব্রেরিতে এটি সম্পর্কে কিছুই থাকে না। কেউ আশা করতে পারে যে কোনও সময় কোনও ওপেন সোর্স লাইব্রেরি নিউগেটেবল হতে পারে তবে আমি স্বীকার করি এটি একটি ছোট উঁচু জায়গা। অন্যদিকে System.IO.DriveInfo এবং অন্যদের কাছে কেবল বাইট রয়েছে (যতক্ষণ না) বরং এটি পরিষ্কার।
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)
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);
}
এখন কয়েকটি ইউনিটে 12 জিবি র্যাম রূপান্তর করা যাক:
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;
}
আমি আমার প্রকল্পের জন্য এটি কোনও ইউডাব্লুপি ডেটাবাইন্ডিং কনভার্টারে অন্তর্ভূক্ত করেছি এবং ভেবেছিলাম এটি অন্যের পক্ষেও কার্যকর হতে পারে।
কোডটি হ'ল:
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.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}}" />
ওহে প্রেস্টো। ম্যাজিক হয়।