gpt4 book ai didi

C++ 像这样将数组从 char 转换为 unsigned int 是否正确且安全?

转载 作者:行者123 更新时间:2023-11-27 23:18:16 25 4
gpt4 key购买 nike

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

最佳答案

对于这样一个简单的任务来说,代码太多了,您只需要这个。

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> ()
};

关于C++ 像这样将数组从 char 转换为 unsigned int 是否正确且安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15065446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com