字节单位换算公式:
1 GB = 1024 MB
1 MB = 1024 KB
1 KB = 1024 Bytes
1 Byte = 8 bits
将字节单位转化为目标单位
根据公式我写了一段C++代码,用于将输入的以字节为单位的数值,转换为目标单位数值。代码中的枚举类型用的是C++11的语法。
enum class Unit{
Byte, KB, MB, GB, TB, PB, EB
};
double convert(double size, Unit unit)
{
double result = size;
switch (unit)
{
case Unit::EB:
result /= 1024; // flow through
case Unit::PB:
result /= 1024; // flow through
case Unit::TB:
result /= 1024; // flow through
case Unit::GB:
result /= 1024; // flow through
case Unit::MB:
result /= 1024; // flow through
case Unit::KB:
result /= 1024; // flow through
case Unit::Byte:
result /= 1;
default:
break;
}
return result;
}
测试代码:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double size = 2.4 * std::pow(1024, 3); // 2.4GB
cout << convert(size, Unit::Byte) << "Byte" << endl;
cout << convert(size, Unit::KB) << "KB" << endl;
cout << convert(size, Unit::MB) << "MB" << endl;
cout << convert(size, Unit::GB) << "GB" << endl;
cout << convert(size, Unit::TB) << "TB" << endl;
cout << convert(size, Unit::PB) << "PB" << endl;
cout << convert(size, Unit::EB) << "EB" << endl;
return 0;
}
运行结果:
2.57698e+009Byte
2.51658e+006KB
2457.6MB
2.4GB
0.00234375TB
2.28882e-006PB
2.23517e-009EB
将字节单位转化为合适的单位
上面的代码中必须指定目标单位,但很多时候我不知道目标单位,只要转化后的单位看上去比较合理(数值介于1-1024之间)即可,所以又写了下面这段代码,输入以字节为单位的数值,返回一个二元组,该而二元组包含了转换后的大小以及单位。
std::pair<double, Unit> convert(double size)
{
std::pair<double, Unit> result = std::make_pair(size, Unit::Byte);
while (result.first >= 1024)
{
result.first /= 1024;
result.second = static_cast<Unit>(1 + static_cast<int>(result.second));
}
return result;
}
测试代码:
std::pair<double, Unit> result = convert(size);
cout << result.first; // 输出结果: 2.4GB
switch (result.second)
{
case Unit::Byte:
cout << "Byte" << endl; break;
case Unit::KB:
cout << "KB" << endl; break;
case Unit::MB:
cout << "MB" << endl; break;
case Unit::GB:
cout << "GB" << endl; break;
case Unit::TB:
cout << "TB" << endl; break;
case Unit::PB:
cout << "PB" << endl; break;
case Unit::EB:
cout << "EB" << endl; break;
default: break;
}
时间: 2024-10-07 05:50:09