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
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
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");
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);
}