C++中如何正确交换std::byteswap成员位字段。

huangapple go评论69阅读模式
英文:

What is the proper way to std::byteswap member bitfields in C++

问题

The proper way to convert deserialized big-endian Header to little-endian Header is to manually swap the byte order of each field in the struct. You can use bitwise operations like shifting and masking to achieve this. Here's an example of how you can do it in C++:

Header bigEndianHeader; // Assume you have the deserialized big-endian Header

Header littleEndianHeader;
littleEndianHeader.magic_value = bigEndianHeader.magic_value;
littleEndianHeader.offset = bigEndianHeader.offset;

// For the flags, you can swap the order using bitwise operations
littleEndianHeader.flag1 = bigEndianHeader.flag8;
littleEndianHeader.flag2 = bigEndianHeader.flag7;
littleEndianHeader.flag3 = bigEndianHeader.flag6;
littleEndianHeader.flag4 = bigEndianHeader.flag5;
littleEndianHeader.flag5 = bigEndianHeader.flag4;
littleEndianHeader.flag6 = bigEndianHeader.flag3;
littleEndianHeader.flag7 = bigEndianHeader.flag2;
littleEndianHeader.flag8 = bigEndianHeader.flag1;

This code manually swaps the byte order for each field in the struct to convert it from big-endian to little-endian.

英文:

I need to convert struct fields that came via network as raw bytes from big-endian to little-endian.

Consider the following struct:

struct [[gnu::packed]] Header {
    std::uint8_t magic_value:4;
    std::uint8_t offset:4;
    std::uint8_t flag1:1;
    std::uint8_t flag2:1;
    std::uint8_t flag3:1;
    std::uint8_t flag4:1;
    std::uint8_t flag5:1;
    std::uint8_t flag6:1;
    std::uint8_t flag7:1;
    std::uint8_t flag8:1;
}; 

What is the proper way to convert deserialized big-endian Header to little-endian Header?

答案1

得分: 2

你可以使用 std::bit_cast

const auto big_endian_data = std::bit_cast<std::uint16_t>(input);
const auto small_endian_data = std::byteswap(big_endian_data);
auto header = std::bit_cast<Header>(small_endian_data);
英文:

You can use std::bit_cast.

const auto big_endian_data = std::bit_cast&lt;std::uint16_t&gt;(input);
const auto small_endian_data = std::byteswap(big_endian_data);
auto header = std::bit_cast&lt;Header&gt;(small_endian_data);

huangapple
  • 本文由 发表于 2023年4月13日 14:44:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定