我有不同的字符串值,格式为“240.2 KB”,“13.8 MB”,“675字节”等等。
任何人都可以帮我弄清楚如何将这些字符串值转换为数字格式,同时考虑到MB和KB
答案 0 :(得分:3)
做这样的事情:
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");
}
现在,您可以像这样使用它:
long result = ConvertDataSize("240.2 KB");
答案 1 :(得分:2)
将单位因子存储在字典中:
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!)
};
我正在使用二进制左移运算符以获得2的幂。不要忘记指定长指示符“L”。否则它将假定为int
。
你得到了字节数(为了简单起见我省略了检查):
private long ToBytes(string s)
{
string[] parts = s.Split(' ');
decimal n = Decimal.Parse(parts[0]);
return (long)(units[parts[1]] * n);
}