C++像这样将数组从char转换为unsigned int正确且安全吗
C++ Is it proper and safe to convert an array from char to unsigned int like this?
目标:正确快速地将数组从char转换为无符号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;
有什么事吗?:如果有更好的方法来完成目标,请在下面发帖!
更多:有可能将这个概念应用于无符号int std::向量吗?
对于这样一个简单的任务来说,代码太多了,你只需要这个。
std::vector <unsigned int> v;
std::copy (std::istream_iterator <char> (iFile),
std::istream_iterator <char> (),
std::back_inserter (v));
或者更短(感谢@1111111(:
std::vector <unsigned int> v
{
std::istream_iterator <char> (iFile),
std::istream_iterator <char> ()
};
vector<char> buf(file_size);
/* read file to &buf[0] */
vector<unsigned int> uints(buf.size());
copy(buf.begin(), buf.end(), uints.begin());
您的原始新/删除用法并非异常安全。经验法则:永远不要在代码中写delete,只要你自己没有写析构函数。此外,"char"可能是签名的,不确定您期望的行为。
相关文章:
- 从不同线程使用int64的不同字节安全吗
- 为什么在全局范围内使用"extern int a"似乎不行?
- 为表示一个或多个操作的C++函数的int参数寻找类型安全的替换
- 为什么我的 std::atomic<int> 变量不是线程安全的?
- 最有效的安全方法将 std::map<int, std::shared_ptr> 转换为 std::<Base>map<int, std::shared_ptr<D
- 将无符号的 int 与 std::string::size_type 进行比较是否安全
- 从std::round转换为int是否安全
- 读取即将在没有同步的情况下同时增加的int是安全的吗?
- 有没有一种安全的方法可以迭代 std::unique_ptr<int[]>?
- 将 -1 分配给无符号 int 以获得最大值是否安全
- 在C++中递增未初始化的 int 是否安全
- 我可以制作一个线程安全的 std::atomic<vector<int>>吗?
- 将矢量<int>分配给矢量是否安全<double>?
- 使用 shared_ptrs 对<无符号 int、boost::any> 类型的通用容器的线程安全实现
- 在unsigned int和signed int之间进行安全转换
- 将intptr_t传递给期望int类型的函数是否安全?
- 如果允许将int赋值给float(反之亦然),是否不类型安全?
- 在可变进模板展开中增加int值的安全方法是什么?
- C++像这样将数组从char转换为unsigned int正确且安全吗
- 在 C++03 中通过 int 运输双精度是否安全