Skip to content

Commit b689178

Browse files
Add a ToDataSize extension
1 parent d6aa9f2 commit b689178

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Src/Autarkysoft.Bitcoin/ExtentionsAndHelpers.cs

+27
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,33 @@ public static string ToOrdinal(this int i)
458458
/// <param name="i">The 32-bit unsigned integer to reverse</param>
459459
/// <returns>The 32-bit signed uninteger result with reverse endianness</returns>
460460
public static uint SwapEndian(this uint i) => (i >> 24) | (i << 24) | ((i >> 8) & 0xff00) | ((i << 8) & 0xff0000);
461+
462+
/// <summary>
463+
/// Converts the given 64-bit signed integer to binary data size (byte, kilo-byte, mega-byte, etc.)
464+
/// </summary>
465+
/// <param name="val">64-bit signed integer</param>
466+
/// <returns>Data size</returns>
467+
public static string ToDataSize(this long val)
468+
{
469+
if (val < 0)
470+
{
471+
return "Invalid (negative) size.";
472+
}
473+
474+
decimal size = val;
475+
int index = 0;
476+
while (size >= 1000 && index < SizeSuffix.Length - 1)
477+
{
478+
index++;
479+
size /= 1024;
480+
}
481+
482+
return $"{(index == 0 ? $"{size:n0}" : (size < 10 ? $"{size:n2}" : (size < 100 ? $"{size:n1}" : $"{size:n0}")))}" +
483+
$" {SizeSuffix[index]}";
484+
}
485+
486+
// exabyte is 10^18 and same size as long.MaxValue
487+
private static readonly string[] SizeSuffix = { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
461488
}
462489

463490

Src/Tests/Bitcoin/ExtentionsAndHelpersTests/IntegerExtensionTests.cs

+22
Original file line numberDiff line numberDiff line change
@@ -69,5 +69,27 @@ public void SwapEndian_UIntTest(uint val, uint expected)
6969
{
7070
Assert.Equal(expected, val.SwapEndian());
7171
}
72+
73+
[Theory]
74+
[InlineData(-1, "Invalid (negative) size.")]
75+
[InlineData(0, "0 B")]
76+
[InlineData(1, "1 B")]
77+
[InlineData(999, "999 B")]
78+
[InlineData(1000, "0.98 KB")] // 0.9765 rounded up with 2 decimal places
79+
[InlineData(1024, "1.00 KB")] // 1.0000 with 2 decimal places
80+
[InlineData(1030, "1.01 KB")] // 1.0058 rounded up
81+
[InlineData(10240, "10.0 KB")] // 1 decimal place
82+
[InlineData(102400, "100 KB")] // 0 decimal place
83+
[InlineData(153600, "150 KB")] // 0 decimal place
84+
[InlineData(1032192, "0.98 MB")] // 0.984375
85+
[InlineData(1024L * 1024, "1.00 MB")]
86+
[InlineData(1024L * 1024 * 1024, "1.00 GB")]
87+
[InlineData(1024L * 1024 * 1024 * 1024, "1.00 TB")]
88+
[InlineData(1024L * 1024 * 1024 * 1024 * 1024, "1.00 PB")]
89+
[InlineData(1024L * 1024 * 1024 * 1024 * 1024 * 1024, "1.00 EB")]
90+
public void ToDataSizeTest(long val, string expected)
91+
{
92+
Assert.Equal(expected, val.ToDataSize());
93+
}
7294
}
7395
}

0 commit comments

Comments
 (0)