views:

49

answers:

1

I'm developing a Python module in C that parses a very efficient protocol which uses dynamic integer sizes. Integers sent using this protocol can range in size from the equivalent of C's 'short' to a 'long long.'

The protocol has a byte that specifies the type of variable being sent (from short to long long), but I'm not sure how to deal with this in code. Right now, I'm setting up a void pointer and allocating memory in the size of the value being sent -- then using atoi, atol, and atoll to set that pointer. The problem is, I need to be able to access that value, and am unable to do so without it being cast later.

What are some good ways to handle this issue?

+4  A: 

Either always store it in a long long locally, or put it in a struct composed of a flag for the size and a union of all the possible types.

Ignacio Vazquez-Abrams
I'm a little confused about how to use a struct/union for that.. Have a quick example?
`typdef struct {`` char flag;`` union {`` unsigned char ubyte;`` unsigned long ulong;`` unsigned long long ulonglong;`` }``} mystruct`
Ignacio Vazquez-Abrams
Then you'd just always cast the union as a long long when you're accessing it in code? Or do you have to switch off of that flag and cast accordingly?
You switch off `.flag` and read the appropriate member (`.ubyte`, `.ulong`, etc.).
Ignacio Vazquez-Abrams
Thanks a lot! Gonna stick with using long longs locally.
The first part of this answer, always using a long long, is going to be easier for you without any loss, compared to the second part of using a union.
Roger Pate
That's what I figured -- just was trying to decide if it was efficient to do so -- doing it with a union will definitely be a pain if I have to switch off of that flag each time.