我的项目中有这两个函数,可将字符数组转换为基本类型(cast_chunk),反之亦然(uncast_type)。

它们很丑陋,并且依赖C++编译器中的基本假设。在std或boost中有什么我可以替换的东西吗?

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

谢谢

最佳答案

boost::endian库同时提供conversion functionstypes with specified endianness

最类似于您正在执行的四个功能是:

template <class T> void native_to_big(T& x);
template <class T> void native_to_little(T& x);
template <class T> void big_to_native(T& x);
template <class T> void little_to_native(T& x);

template <class T> void native_to_big(T source, T& target);
template <class T> void native_to_little(T source, T& target);
template <class T> void big_to_native(T source, T& target);
template <class T> void little_to_native(T source, T& target);

关于c++ - C++-独立于平台的函数,用于将字节数组转换为值,反之亦然,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8867482/

10-10 09:41