How to convert Bytes To Kilobytes in C#

By FoxLearn 11/9/2024 1:01:06 PM   39
To convert bytes to kilobytes (KB) in C#, you simply divide the number of bytes by 1024, since 1 kilobyte (KB) is equal to 1024 bytes.

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.

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`.

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:

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`.

dotnet add package Humanizer