目標:正確快速地將數組從char轉換爲unsigned int。C++將數組從char轉換爲unsigned int是否正確又安全?
檢查我的工作 - 請:
...
// NOTE:
// m_chFileBuffer is a member/variable from a class.
// m_nFileSize is also a member/variable from a class.
// iFile is declared locally as std::ifstream
// Calculate the size of iFile and copy the calculated
// value to this->m_nFileSize
iFile.seekg(0, std::ios::end);
this->m_nFileSize = iFile.tellg();
iFile.seekg(0, std::ios::beg);
// Declare this->m_chFileBuffer as a new char array
this->m_chFileBuffer = new char[ this->m_nFileSize ];
// Read iFile into this->m_chFileBuffer
iFile.read(this->m_chFileBuffer, this->m_nFileSize);
// Declare a new local variable
::UINT *nFileBuffer = new ::UINT[ this->m_nFileSize ];
// Convert this->m_chFileBuffer from char to unsigned int (::UINT)
// I might be doing this horribly wrong, but at least I tried and
// will end up learning from my mistakes!
for(::UINT nIndex = 0; nIndex != this->m_nFileSize; nIndex ++)
{
nFileBuffer[ nIndex ] = static_cast<::UINT>(this->m_chFileBuffer[ nIndex ]);
// If defined DEBUG, print the value located at nIndex within nFileBuffer
#ifdef DEBUG
std::cout << nFileBuffer[ nIndex ] << ' ';
#endif // DEBUG
}
// Do whatever with nFileBuffer
...
// Clean-up
delete [ ] nFileBuffer;
得到的東西?: 如果有更好的方法來完成目標,請後下!
更多: 是否有可能將此概念應用於unsigned int std :: vector?
不確定你究竟是什麼,但是你顯示的代碼沒有任何安全性,所有擁有指針的原始指針都可能泄漏。 – 111111 2013-02-25 11:03:22
我該如何解決這個問題? D: – CLearner 2013-02-25 11:04:28
該文件的內容是什麼,「nFileBuffer」的期望內容是什麼? – 111111 2013-02-25 11:06:51