Hi everyone!

These are my first code snippets. These were written as part of my CSIT project and are used to convert sizes and frequencies easily from one type to another. First lets look at the byte conversion function.

[cc lang=”c#”]

public enum ByteUnits : int

{

B,

kB,

MB,

GB,

TB,

PB

}

public static string Bytes2Size(double value, ByteUnits fromType = ByteUnits.B)

{

// If the bytes are 0 then we can logically go no further.

if (value == 0)

{

return “0 B”;

}

// First we need to convert the value back into the smallest unit.

double from = (value * Math.Pow(1024, (double)fromType));

// This will give us the index of the best size to use.

double exponent = Math.Floor(Math.Log(from) / Math.Log(1024));

// Return the processed value.

return (from / Math.Pow(1024, exponent)).ToString(“n2″) + ” ” + Enum.GetName(typeof(ByteUnits), (int)exponent);

}

[/cc]

As you can see the code above is relatively simple. Here is a a basic description of the process:

**lines 9 – 11**do a check to ensure that no 0’s fall into the function. Since, if they did, it would break the result.**Line 15**converts the original value into the most basic unit that this type supports. In the case of the example above it converts the value back into bytes.**Line 18**gathers the exponent. This will represent the index of the enumeration that the value should be converted into (basically anyway).**Line 21**converts the value and then adds the symbol thanks to some .NET magic, then returns the result.

As you can see, these are pretty simple. They just contain the sets of units to be used in the conversions. One of the best features of this approach is that you simply need to add the symbol for the next unit to be able to translate to that higher unit. Simple no? I also promised you a version of the above function that converts the hertz unit – so here it is.

[cc lang=”c#”]

public enum HertzUnits : int

{

Hz,

KHz,

MHz,

GHz,

THz,

PHz

}

public static string Hertz2Frequency(double value, HertzUnits fromType = HertzUnits.Hz)

{

// If the bytes are 0 then we can logically go no further.

if (value == 0)

{

return “0 Hz”;

}

// Get the original value.

double from = (value * Math.Pow(1000, (double)fromType));

// This will give us the index of the best size to use.

double exponent = Math.Floor(Math.Log(from) / Math.Log(1000));

// Return the processed value.

return (from / Math.Pow(1000, exponent)).ToString(“n2″) + ” ” + Enum.GetName(typeof(HertzUnits), (int)exponent);

}

[/cc]

I hope you enjoyed this snippet. If you have anything you wish to say or suggest feel free to comment.