How to convert Bytes To Kilobytes in C#
By Tan Lee Published on Nov 09, 2024 316
The value of 1024 is used in the context of binary prefixes such as kibibytes (KiB), mebibytes (MiB), gibibytes (GiB), and tebibytes (TiB), which represent powers of 2 (2^10 = 1024).
Use 1000 or 1024 for size conversions depending on the level of accuracy you need. Both values will provide a rough estimate of sizes, with 1000 aligning with decimal-based metrics and 1024 used for binary-based metrics, allowing you to choose the level of precision that best fits your needs.
1 2 3 4 5 6 7 8 |
private enum Kinds { Bytes = 0, Kilobytes = 1, Megabytes = 2, Gigabytes = 3, Terabytes = 4, } |
To convert a higher-order unit like megabytes to bytes, multiply the value by `1024^N` (where N is the number of steps between the units). For megabytes to bytes, N is 2, so you multiply by `1024^2`. To reverse the process, divide the value by `1024^2`.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static class Converter { public static double KilobytesToBytes( double kilobytes) => From(kilobytes, Kinds.Kilobytes); public static double MegabytesToBytes( double megabytes) => From(megabytes, Kinds.Megabytes); public static double GigabytesToBytes( double gigabytes) => From(gigabytes, Kinds.Gigabytes); public static double TerabytesToBytes( double terabytes) => From(terabytes, Kinds.Terabytes); public static double ToKilobytes( double bytes) => To(bytes, Kinds.Kilobytes); public static double ToMegabytes( double bytes) => To(bytes, Kinds.Megabytes); public static double ToGigabytes( double bytes) => To(bytes, Kinds.Gigabytes); public static double ToTerabytes( double bytes) => To(bytes, Kinds.Terabytes); private static double To( double value, Kinds kind) => value / Math.Pow(1024, ( int )kind); private static double From( double value, Kinds kind) => value * Math.Pow(1024, ( int )kind); } |
You can easily use Humanizer library to help you convert byte to kilobyte.
Humanizer is a library that simplifies working with strings, enums, dates, times, timespans, numbers, and quantities. It includes a type called `ByteSize` that provides convenient helper functions to convert between different size units. The advantage of using this type is that the core value remains consistent, allowing for quick and accurate conversions between various size units.
For example:
1 2 3 4 5 6 7 |
var size = (10).Kilobytes(); size.Bits // 81920 size.Bytes // 10240 size.Kilobytes // 10 size.Megabytes // 0.009765625 size.Gigabytes // 9.53674316e-6 size.Terabytes // 9.31322575e-9 |
To get started, simply install the latest version using the `dotnet-cli`.
1 |
dotnet add package Humanizer |
- Primitive types in C#
- How to set permissions for a directory in C#
- How to Convert Int to Byte Array in C#
- How to Convert string list to int list in C#
- How to convert timestamp to date in C#
- How to Get all files in a folder in C#
- How to use Channel as an async queue in C#
- Case sensitivity in JSON deserialization