我的项目中有两个职能,将一个特性阵列改为一个基本类型(播种-草),另一个是围绕(uncast_type)。
They are ugly and rely on underlying assumptions in the C++ compiler. Is there anything in std or boost that I can replace these with?
typedef uint8_t byte;
typedef std::vector<byte> data_chunk;
template<typename T>
T cast_chunk(data_chunk chunk, bool reverse=false)
{
#ifdef BOOST_LITTLE_ENDIAN
// do nothing
#elif BOOST_BIG_ENDIAN
reverse = !reverse;
#else
#error "Endian isn t defined!"
#endif
if (reverse)
std::reverse(begin(chunk), end(chunk));
T val = 0;
for (size_t i = 0; i < sizeof(T) && i < chunk.size(); ++i)
val += static_cast<T>(chunk[i]) << (i*8);
return val;
}
template<typename T>
data_chunk uncast_type(T val, bool reverse=false)
{
#ifdef BOOST_LITTLE_ENDIAN
// do nothing
#elif BOOST_BIG_ENDIAN
reverse = !reverse;
#else
#error "Endian isn t defined!"
#endif
data_chunk chunk;
for (size_t i = 0; i < sizeof(T); ++i)
chunk.push_back(reinterpret_cast<byte*>(&val)[i]);
if (reverse)
std::reverse(begin(chunk), end(chunk));
return chunk;
}
通常如何使用:
uint64_t val = 110;
data_chunk byte_array = uncast_type(val);
assert(val == cast_chunk<uint64_t>(byte_array);
增 编