How do I convert between big-endian and little-endian values in C++?

前端 未结 30 2525
难免孤独
难免孤独 2020-11-21 23:18

How do I convert between big-endian and little-endian values in C++?

EDIT: For clarity, I have to translate binary data (double-precision floating point values and 3

30条回答
  •  清酒与你
    2020-11-22 00:08

    Most platforms have a system header file that provides efficient byteswap functions. On Linux it is in . You can wrap it nicely in C++:

    #include 
    
    #include 
    
    template struct SizeT {};
    
    #define BYTESWAPS(bits) \
    template inline T htobe(T t, SizeT) { return htobe ## bits(t); } \
    template inline T htole(T t, SizeT) { return htole ## bits(t); } \
    template inline T betoh(T t, SizeT) { return be ## bits ## toh(t); } \
    template inline T letoh(T t, SizeT) { return le ## bits ## toh(t); }
    
    BYTESWAPS(16)
    BYTESWAPS(32)
    BYTESWAPS(64)
    
    #undef BYTESWAPS
    
    template inline T htobe(T t) { return htobe(t, SizeT()); }
    template inline T htole(T t) { return htole(t, SizeT()); }
    template inline T betoh(T t) { return betoh(t, SizeT()); }
    template inline T letoh(T t) { return letoh(t, SizeT()); }
    
    int main()
    {
        std::cout << std::hex;
        std::cout << htobe(static_cast(0xfeca)) << '\n';
        std::cout << htobe(0xafbeadde) << '\n';
    
        // Use ULL suffix to specify integer constant as unsigned long long 
        std::cout << htobe(0xfecaefbeafdeedfeULL) << '\n';
    }
    

    Output:

    cafe
    deadbeaf
    feeddeafbeefcafe
    

提交回复
热议问题