【问题标题】:C++ Convert string to 16-bit unsigned/signed int/floatC++ 将字符串转换为 16 位无符号/有符号整数/浮点数
【发布时间】:2016-01-24 14:18:29
【问题描述】:

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

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

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

【问题讨论】:

  • “那么,是否可以将字符串转换为 16 位 int/float?” 可以,您检查过atof()吗?
  • 只需使用std::stoi
  • std::stoistd::stof 怎么样。
  • 所有这些都自动转换为 16 位吗? AFAIK 他们只转换为 32-it
  • @philsegeler 你有什么疑问?这些转换为您作为接收变量所拥有的内容。如果它是 16 位宽,则不会有更大的结果。

标签: c++ string floating-point int


【解决方案1】:

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

#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::cout
【解决方案2】:

对于顶点坐标,您有一个浮点数 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;

【讨论】:

    猜你喜欢
    • 2011-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 2012-01-09
    • 1970-01-01
    • 2011-06-14
    相关资源
    最近更新 更多