2016-01-24 803 views
-2

我正在製作一個簡單程序,它從文件(uints和浮點數)加載頂點和三角形。C++將字符串轉換爲16位無符號/有符號整型/浮點型

他們將在OpenGL中使用,我希望他們是16位(以節省內存),但我只知道如何轉換爲32位。我不想使用匯編,因爲我希望它也可以在ARM上運行。

那麼,是否有可能將一個字符串轉換爲一個16位的int/float?

+4

_「那麼,是不是可以轉換一個字符串到一個16位整數/浮點數?「_當然是,你檢查'atof()'? –

+0

只需使用['std :: stoi'](http://en.cppreference.com/w/cpp/string/basic_string/stol)。 –

+0

['std :: stoi'](http://en.cppreference.com/w/cpp/string/basic_string/stol)或['std :: stof'](http://en.cppreference。 COM/W/CPP /串/ basic_string的/ STOF)。 –

回答

2

一個可能的答案會是這樣的:

#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)); 
+0

所以這將投射整數/浮點數,它將具有相同的值? – philsegeler

+0

對我來說,測試: \t std :: cout << myInt16 <<「\ n」; // 345 \t std :: cout << myFloat <<「\ n」; //3.45 – Actaea

0

對於頂點座標,您有一個浮點數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; 
相關問題