8

I am using bitfields to get easy access on a float library I am trying to make for a microcontroller with no FPU.

The problem is that I can't seem to make it work with bitfields. Take a look:

typedef struct
{
   union{
    unsigned long mantissa: 23;
    unsigned long exponent: 8;
    unsigned long sign: 1;
    float all;

      };

}_float __attribute__((__packed__));

The problem is that when I try to access or change anything it considers the bitfields as 1,8,23 bits from the end respectively. While it should be 23 bits from the end, then 8 bits and then the last bit. Unless I have totally misunderstood the use of bitfields. I thought that using packed would solve the problem but as you can see it didn't.

Any help would be really appreciated. I have been lead to this site while googling more than once so I have high hopes.

ctuffli
  • 3,559
  • 4
  • 31
  • 43

3 Answers3

18

You might be missing a struct inside your union.

typedef struct
{
    union{
       struct {
           unsigned long mantissa: 23;
           unsigned long exponent: 8;
           unsigned long sign: 1;
       } float_parts;
       float all;
    };
}_float __attribute__((__packed__));

Note that the order of mantissa/exponent and sign depends one the endianess of the cpu.

epatel
  • 45,805
  • 17
  • 110
  • 144
  • Thank you for your input but why add a struct inside the union? I made the union of the float's parts with the float to make sure that each bitfield corresponds to the appropriate part of the float. Isn't that enough? –  Feb 25 '09 at 19:14
  • 1
    a union will make ALL its members share the same memory. I don't think using bitfields will change this behavior, so all your bitfields start at bit 0, just like the "all" float does. Putting them in a struct makes the laid out sequentially. – rmeador Feb 25 '09 at 19:18
  • You were absolutely right! That's what was needed. I blame my understanding of union then :) . Thank you friend, now I am able to access any part of my float at will. –  Feb 25 '09 at 19:26
0

The problem is that it is a union. It should be 'struct'.

Antti Huima
  • 25,136
  • 3
  • 52
  • 71
0

If you are on a glibc platform you can take a look on the ieee754.h header file. It takes care about the endianess stuff. If not it's still probably worth to take a look on it.

quinmars
  • 11,175
  • 8
  • 32
  • 41