2013-02-25 29 views
0

目标:正确快速地将数组从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?

+1

不确定你究竟是什么,但是你显示的代码没有任何安全性,所有拥有指针的原始指针都可能泄漏。 – 111111 2013-02-25 11:03:22

+0

我该如何解决这个问题? D: – CLearner 2013-02-25 11:04:28

+0

该文件的内容是什么,“nFileBuffer”的期望内容是什么? – 111111 2013-02-25 11:06:51

回答

4

对于这么简单的任务来说代码太多了,你需要的只是这个。

std::vector <unsigned int> v; 
std::copy (std::istream_iterator <char> (iFile), 
      std::istream_iterator <char>(), 
      std::back_inserter (v)); 

或者更短(感谢@ 111111):

std::vector <unsigned int> v 
{ 
     std::istream_iterator <char> (iFile), 
     std::istream_iterator <char>() 
}; 
+4

或者更好的只是使用std :: vectors迭代器的构造函数。 'std :: vector v {std :: istream_iterator (iFile),std :: istream_iterator ()};' – 111111 2013-02-25 11:09:08

+0

@aleguna我简直不敢相信那么简单!谢谢。我会在大约2分钟内接受这个答案。 – CLearner 2013-02-25 11:14:13

+0

噢,也谢谢你@ 111111 – CLearner 2013-02-25 11:14:53

0
vector<char> buf(file_size); 
/* read file to &buf[0] */ 
vector<unsigned int> uints(buf.size()); 
copy(buf.begin(), buf.end(), uints.begin()); 

你生新/删除使用率也不例外安全。经验法则:不要在你的代码中写入删除,只要你不是自己编写析构函数。此外,“char”可能会被签名,但不确定你期望在那里有什么行为。

+0

等等,所以如果我在一个类函数块中局部声明了一个数组,我可以在解构器中删除它吗?你确定? O.o – CLearner 2013-02-25 11:16:49

+0

@CLearner不知道你从哪里得到的,但:不。当然不是。 Oo – cooky451 2013-02-25 11:18:10

+0

与您阅读的内容混淆。而且我知道。谢谢(你的)信息。不知道为什么你的帖子是-1,但我+1。 – CLearner 2013-02-25 11:20:14