I have two int16_t
integers that I want to store in one one 32-bit int.
I can use the lower and upper bits to do this as answered in this question.
The top answers demonstrates this
int int1 = 345;
int int2 = 2342;
take2Integers( int1 | (int2 << 16) );
But my value could also be negative, so will << 16
cause undefined behavior?
If so, what is the solution to storing and retrieving those two numbers which can also be negative in a safe way?
Further context
The whole 32 bit number will be stored in an array with other numbers similar to it.
These numbers will never be utilized as a whole, I'll only want to work with one of the integers packed inside at once.
So what is required is two functions which ensure safe storing and retrieval of two int16_t
values into one 4 byte integer
int pack(int16_t lower, int16_t upper);
int16_t get_lower(int);
int16_t get_upper(int);