Casting pointer type based on integer size (C99)

c, c99, casting, pointers

Solution

You can use a struct, it's not elegant but sounds like what you're looking for. Note that you must define the struct alignment to 1 byte. You're also limited to 64bit.

typedef struct Int24 {
    int value : 24;
} Int;

typedef struct UInt24 {
    unsigned value  : 24;
} UInt24;

typedef struct Int48 {
    long long value : 48;
} Int48;

With templates:

template<int bytes> struct Int {
    long long value : bytes * 8;
};
typedef Int<1> Int8;
typedef Int<6> Int48;

With macro:

#define DECL_INT(n)          \
    typedef struct _Int##n { \
      long long value : n;   \
    } Int##n

// declaration of type
DECL_INT(48); // produces Int48

// usage
Int48 i48;

Problem

How do you (if possible) define a type by an integer size? For example if I wanted to make a type which was 3 bytes long how could I accomplish doing something like this? (I am aware this is incorrect) ``` typedef int24_t 3; ``` I am trying to write a generalized function which takes a character string parameter containing multiple numbers, and stores the numbers in a pointer, passed as another parameter. However I want to make it so you can pass a numerical parameter which determines how big the variable type storing the numbers will be: i.e. if it were 1 the type could be char, if it were 4 the type could be int etc. I am aware that it is possible to just store the number in a temporary fixed size variable, and then only copy the relevant bytes to the pointer depending on the requested size, but I want the code to be portable and I don't want to be messing around with Endianness as I've had trouble with that in the past. Thanks

Original source