0

I have different string values in the format "240.2 KB", "13.8 MB", "675 bytes" and so on.

Can anyone help me figure out how to convert these string values to numeric format also taking into consideration the MBs and KBs

0xMB
  • 871
  • 1
  • 8
  • 15
user2327795
  • 1,677
  • 4
  • 13
  • 16
  • 1
    Of course, post what you have tried so that we can show how to fix it. – Eser Sep 11 '15 at 18:11
  • could not figure out any proper logic yet. All I could find online are the ones telling you how to convert a file size in numeric format to String. – user2327795 Sep 11 '15 at 18:12
  • Here is my guid. Very simple. Use Split method to split string by space. Then switch on second element of given array. Multiply value from first element by 1024,etc – M.kazem Akhgary Sep 11 '15 at 18:16
  • see http://stackoverflow.com/questions/14488796/does-net-provide-an-easy-way-convert-bytes-to-kb-mb-gb-etc – bashkan Sep 11 '15 at 18:17
  • Specifically look at this [answer](http://stackoverflow.com/a/22366422/302918) to the question @serbasi commented on. – juharr Sep 11 '15 at 18:19

2 Answers2

3

Do something like this:

public long ConvertDataSize(string str)
{
    string[] parts = str.Split(' ');

    if (parts.Length != 2)
        throw new Exception("Unexpected input");

    var number_part = parts[0];

    double number = Convert.ToDouble(number_part);

    var unit_part = parts[1];

    var bytes_for_unit = GetNumberOfBytesForUnit(unit_part);

    return Convert.ToInt64(number*bytes_for_unit);

}

private long GetNumberOfBytesForUnit(string unit)
{

    if (unit.Equals("kb", StringComparison.OrdinalIgnoreCase))
        return 1024;

    if (unit.Equals("mb", StringComparison.OrdinalIgnoreCase))
        return 1048576;

    if (unit.Equals("gb", StringComparison.OrdinalIgnoreCase))
        return 1073741824;

    if (unit.Equals("bytes", StringComparison.OrdinalIgnoreCase))
        return 1;

    //Add more rules here to support more units

    throw new Exception("Unexpected unit");
}

Now, you can use it like this:

long result = ConvertDataSize("240.2 KB");
Yacoub Massad
  • 27,509
  • 2
  • 36
  • 62
2

Store the unit factors in a dictionary:

Dictionary<string, long> units = new Dictionary<string, long>() {
    { "bytes", 1L },
    { "KB", 1L << 10 }, // kilobytes
    { "MB", 1L << 20 }, // megabytes
    { "GB", 1L << 30 }, // gigabytes
    { "TB", 1L << 40 }, // terabytes
    { "PB", 1L << 50 }, // petabytes
    { "EB", 1L << 60 }  // exabytes (who knows how much memory we'll get in future!)
};

I am using the binary left shift operator in order to get the powers of 2. Don't forget to specify the long specifier "L". Otherwise it will assume int.

You get the number of bytes with (I omitted checks for the sake of simplicity):

private long ToBytes(string s)
{
    string[] parts = s.Split(' ');
    decimal n = Decimal.Parse(parts[0]);
    return (long)(units[parts[1]] * n);
}
Olivier Jacot-Descombes
  • 104,806
  • 13
  • 138
  • 188
  • I removed my answer since I forgot `L`s but don't forget, If you don't specify `CultureInfo.InvariantCulture` in decimal.Parse it will not work in most of the europian countries.... – Eser Sep 11 '15 at 18:33
  • Interesting, we have found almost the same solution! Yet another tweak would be to create the dictionary with `StringComparer.OrdinalIgnoreCase` in order to make the search for units case insensitive. A full solution would also have to check for the right format of the input string, for allowed units and for the successful conversion of the number. It is OK to make corrections to a solution. There is no need to delete it just for a little mistake. – Olivier Jacot-Descombes Sep 11 '15 at 18:40