交换& quot; endianness&"花车和双打 [英] swapping "endianness" of floats and doubles

查看:92
本文介绍了交换& quot; endianness&"花车和双打的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想切换float和double值的字节序",通过执行以下操作可以正常工作:

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?

swap()是gcc内置函数的C ++包装器,在此未提供.

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)

对于某些数据格式(例如CBOR),需要交换字节序.

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.

这篇关于交换&amp; quot; endianness&amp;&quot;花车和双打的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆