简体   繁体   中英

C data type to store double or long or any other data

I want to create c struct that can hold 3 words of 'data'.

struct _Obj {
    ??? a;
    ??? b;
    ??? c;
}
typedef struct _Obj Obj;

But, I want to be able to store different types of data in a, b and c and cast them when needed appropriately.

For example, sometimes 'a' may be a long, other times it'll be a double and still others a pointer. Runtime I will know what is stored in them, so I will want to be able to compile time (instantly) cast them to their datatype when needed.

Obj obj;
long a = 893;
obj.a = a;
double b = 3.14159;
obj.b = b;

long newA = (long)obj.a;
double newB = (double)obj.b;

Basically, I just want to be able to store some bits and then interpret them in a specific fashion later. How do I do this?

Use a union:

union {
    long integer;
    double floating_point;
    void *pointer;
} obj;

You don't need casting here and it's more type-safe than casting. Furthermore, casting isn't necessarily a runtime no-op (on little-endian, probably, but otherwise not), so a union really is your best bet if you want zero casting overhead.

In case you ever want types determined at compile-time, there's also the _Generic feature since C11.

C allows bit reinterpretation.

Just define a binary format for your data, and extract. You can extract floating point types portably, but that's probably overkill here. Probably we can say that the longest datum we will need is the 80 bit double. So 30 bytes should be sufficient, plus two bytes to say what type the data is. So 32 bytes is a nice round power of two number.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM