C++ C++;将字符串转换为16位无符号/有符号整数/浮点

C++ C++;将字符串转换为16位无符号/有符号整数/浮点,c++,string,floating-point,int,C++,String,Floating Point,Int,我正在制作一个简单的程序,从文件(uint和float)加载顶点和三角形 它们将在OpenGL中使用,我希望它们是16位(以节省内存),但我只知道如何转换为32位。我不想使用assembly,因为我希望它也能在ARM上运行 那么,是否可以将字符串转换为16位int/float?对于顶点坐标,您有一个浮点数X,您需要将其转换为OpenGL中的16位备选值之一:GL_SHORT或GL_UNSIGNED_SHORT或GL_HALF_float。首先,您需要决定是使用整数还是浮点 如果使用整数,我建议使

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

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


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

对于顶点坐标,您有一个浮点数X,您需要将其转换为OpenGL中的16位备选值之一:GL_SHORT或GL_UNSIGNED_SHORT或GL_HALF_float。首先,您需要决定是使用整数还是浮点

如果使用整数,我建议使用无符号整数,这样零映射到最小值,65536映射到最大值。对于整数,您需要确定X的有效值范围

假设您知道X在Xmin和Xmax之间。然后,您可以通过以下方式计算GL_无符号_短兼容表示:

unsigned short convert_to_GL_UNSIGNED_SHORT(float x, float xmin, float xmax) {
  if (x<=xmin)
     return 0;
  else if (x>=xmax)
     return 65535;
  else
     return (unsigned short)((X-Xxmin)/(X-Xmax)*65535 + 0.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));
#包括
#包括
std::string str1=“345”;
std::string str2=“3.45”;
int-myInt(std::stoi(str1));
uint16_t myInt16(0);
如果(myInt=0){
myInt16=静态投影(myInt);
}
否则{

std::cout“那么,可以将字符串转换为16位int/float吗?”当然可以,您是否检查了
atof()
?只需使用。或者如何。所有这些是否自动转换为16位?如果它们只转换为32位-it@philsegeler你有什么疑问?这些转换成你的接收变量。如果它是一个16位宽,不会有任何更大的结果。所以这将转换整数/浮点,它将有相同的值?对我来说,做一个使用:std::cout进行测试
#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));