C++将字符串转换为16位无符号/有符号整型/浮点型
我正在制作一个简单程序,它从文件(uints和浮点数)加载顶点和三角形。C++将字符串转换为16位无符号/有符号整型/浮点型
他们将在OpenGL中使用,我希望他们是16位(以节省内存),但我只知道如何转换为32位。我不想使用汇编,因为我希望它也可以在ARM上运行。
那么,是否有可能将一个字符串转换为一个16位的int/float?
一个可能的答案会是这样的:
#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));
所以这将投射整数/浮点数,它将具有相同的值? – philsegeler
对我来说,测试: \t std :: cout Actaea
对于顶点坐标,您有一个浮点数X,您需要将它转换为OpenGL中的16位替代方法之一:GL_SHORT或GL_UNSIGNED_SHORT或GL_HALF_FLOAT。首先,您需要决定是使用整数还是浮点数。
如果你打算用整数,我推荐使用无符号整数,这样零映射到最小值,而65536映射到最大值。对于整数,您需要决定X的有效值范围。
假设您知道X在Xmin和Xmax之间。然后,您可以计算出一个GL_UNSIGNED_SHORT相容表示:如果你有一半花车去
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)
}
,我建议你看看16-bit floats and GL_HALF_FLOAT
的脸索引,你有32个无符号整数,对不对?如果他们都低于65536,您可以轻松地将它们转换为16位无符号短裤由
unsigned short i16 = (unsigned short)i32;
_“那么,是不是可以转换一个字符串到一个16位整数/浮点数?“_当然是,你检查'atof()'? –
只需使用['std :: stoi'](http://en.cppreference.com/w/cpp/string/basic_string/stol)。 –
['std :: stoi'](http://en.cppreference.com/w/cpp/string/basic_string/stol)或['std :: stof'](http://en.cppreference。 COM/W/CPP /串/ basic_string的/ STOF)。 –