-2

If I know I am on a little-endian machine, how can I convert the endiannes of a 14-bit bitfield?

struct {
    unsigned foo : 14, bar 2;
} baz;

I have a hunch that baz.foo = htons(baz.foo) will not work properly.

Matt
  • 21,026
  • 18
  • 63
  • 115
  • 2
    There is no single layout for bit-fields, and therefore no standard conversion from “little-endian bit-fields” to “big-endian bit-fields”. If you specify the layouts you wish to convert from and to, perhaps your question will be answerable, but in its current form, it isn't. – Pascal Cuoq Apr 06 '13 at 20:33
  • 1
    Also note that “endianness” refers to the order of bytes, not of bits. Bits are not addressable so it is not possible to observe how they are stored in memory within a byte even if you try. – Pascal Cuoq Apr 06 '13 at 20:36
  • @PascalCuoq I am using GCC on x86 Linux. So the 2 bits of `bar` would be placed at the most significant bits of the first byte of the struct. – Matt Apr 06 '13 at 20:36
  • `bar` would be in the most significant bits of the least significant byte? Are you sure? – Pascal Cuoq Apr 06 '13 at 20:44
  • My GCC uses full 32-bit `int`s to store bit-fields. Assuming all GCCs do this, and assuming both the source and the destination layouts are GCC-like, it's 32 bits you have to byte-swap. – Pascal Cuoq Apr 06 '13 at 20:47
  • @Matt - when you are on a little endian system, how do you know the order of the bits on the "other" system you want to convert to? Pascal is more than hinting on the problem that we don't know which 14 bits of the `unsigned` will be used to store the value. Or the number of bits in an `unsigned`. – Bo Persson Apr 06 '13 at 23:42

1 Answers1

1

Stick it in a union with a uint16_t and swap that instead.

Lily Ballard
  • 182,031
  • 33
  • 381
  • 347