本文介绍了交换“字节顺序”浮动和双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



 <$ c $ 

我想切换float和double值的字节顺序 c> float const v {1.f};

swap(reinterpret_cast< :: std :: uint32_t const&>(v));

是否存在更好的方法来进行交换,而无需投射?
$ b

编辑: swap()是gcc内置函数的C ++包装器,我没有在这里包含它。 b
$ b

  uint16_t __builtin_bswap16(uint16_t x)
uint32_t __builtin_bswap32(uint32_t x)
uint64_t __builtin_bswap64(uint64_t x)

一些数据格式需要交换字节数,如CBOR。

解决方案

虽然尝试和避免强制转换是一个很好的做法,但这样的用法也是强制转换的原因。一个endian swap是一个原始数据操作,所以为了做到这一点,你必须删除输入信息,我会说,如果它不是endian正确的开始,那么它不是一个浮动,不应该以这种方式键入而在错误的endianess状态。


I'd like to switch the "endianness" of float and double values, it works OK, by doing something like:

float const v{1.f};

swap(reinterpret_cast<::std::uint32_t const&>(v));

Does there exist a better way to do the swap, without a cast?

EDIT: swap() is a C++ wrapper for gcc's built-in functions, I did not include it here.

uint16_t __builtin_bswap16 (uint16_t x)
uint32_t __builtin_bswap32 (uint32_t x)
uint64_t __builtin_bswap64 (uint64_t x)

Swapping of endianess is needed for a some data formats, like CBOR.

解决方案

While it is good practice to try and avoid casts, it's uses like this that are the reason casts exist. An endian swap is a raw data operation so in order to do it you must strip away the typing information, I would say that if it is not endian correct to begin with, then it is not a float and should never have been typed that way while in the wrong endianess state.

这篇关于交换“字节顺序”浮动和双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:17