C++ 将字符串转换为 16 位无符号/有符号 int/float

phi*_*ler 0 c++ string floating-point int

我正在制作一个简单的程序,该程序从文件(uint 和 float)加载顶点和三角形。

它们将在 OpenGL 中使用,我希望它们是 16 位(以节省内存),但我只知道如何转换为 32 位。我不想使用汇编,因为我希望它也可以在 ARM 上运行。

那么,是否可以将字符串转换为 16 位 int/float 呢?

小智 5

一种可能的答案是这样的:

#include <string>
#include <iostream>

std::string str1 = "345";
std::string str2 = "3.45";

int myInt(std::stoi(str1));
uint16_t myInt16(0);
if (myInt <= static_cast<int>(UINT16_MAX) && myInt >=0) {
    myInt16 = static_cast<uint16_t>(myInt);
}
else {
    std::cout << "Error : Manage your error the way you want to\n";
}

float myFloat(std::stof(str2));
Run Code Online (Sandbox Code Playgroud)