Files
Wino-Mail/Wino.Core/Extensions/LongExtensions.cs

58 lines
1.6 KiB
C#
Raw Normal View History

2024-04-18 01:44:37 +02:00
using System;
using System.Collections.Generic;
using System.Text;
2025-02-16 11:54:23 +01:00
namespace Wino.Core.Extensions;
public static class LongExtensions
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
// Returns the human-readable file size for an arbitrary, 64-bit file size
// The default format is "0.### XB", e.g. "4.2 KB" or "1.434 GB"
public static string GetBytesReadable(this long i)
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
// Get absolute value
long absolute_i = (i < 0 ? -i : i);
// Determine the suffix and readable value
string suffix;
double readable;
if (absolute_i >= 0x1000000000000000) // Exabyte
{
suffix = "EB";
readable = (i >> 50);
}
else if (absolute_i >= 0x4000000000000) // Petabyte
{
suffix = "PB";
readable = (i >> 40);
}
else if (absolute_i >= 0x10000000000) // Terabyte
{
suffix = "TB";
readable = (i >> 30);
}
else if (absolute_i >= 0x40000000) // Gigabyte
{
suffix = "GB";
readable = (i >> 20);
}
else if (absolute_i >= 0x100000) // Megabyte
{
suffix = "MB";
readable = (i >> 10);
}
else if (absolute_i >= 0x400) // Kilobyte
{
suffix = "KB";
readable = i;
}
else
2024-04-18 01:44:37 +02:00
{
2025-02-16 11:54:23 +01:00
return i.ToString("0 B"); // Byte
2024-04-18 01:44:37 +02:00
}
2025-02-16 11:54:23 +01:00
// Divide by 1024 to get fractional value
readable = (readable / 1024);
// Return formatted number with suffix
return readable.ToString("0.# ") + suffix;
2024-04-18 01:44:37 +02:00
}
}