将字符串格式的值转换为long格式
本文关键字:格式 long 转换 字符串 | 更新日期: 2023-09-27 18:12:18
我有不同的字符串值,格式为"240.2 KB", "13.8 MB", "675 bytes"等等。
谁能帮我弄清楚如何将这些字符串值转换为数字格式,同时考虑到mb和kb
这样做:
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");
将单位因子存储在字典中:
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);
}