I need to split a 32-bit integer (x) up into an array of individual bytes, and I currently have this code:
This works perfectly well. However, I need to convert multiple ints so I've ended up repeating the same sort of thing multiple times, which is a bit of a no-no.
As you can't easily return an array from a C function, I thought it would be best to create a macro. However, I've never made one before. Here's what I tried:
This compiles and runs, but generates the wrong result. I thought the preprocessor did a direct substitution of the macro into the code, so I would have expected that this would return exactly the same compiled binary. What am I missing? Alternatively, is there a 'better' way to accomplish this without using a macro?
Code:
unsigned char xarray[4] =
{
x & 0xFF,
(x >> 8) & 0xFF,
(x >> 16) & 0xFF,
(x >> 24) & 0xFF
};
This works perfectly well. However, I need to convert multiple ints so I've ended up repeating the same sort of thing multiple times, which is a bit of a no-no.
As you can't easily return an array from a C function, I thought it would be best to create a macro. However, I've never made one before. Here's what I tried:
Code:
#define BYTE_ARRAY(x) (x & 0xFF, (x >> 8) & 0xFF, (x >> 16) & 0xFF, (x >> 24) & 0xFF)
void my_function(blah blah)
{
unsigned char xarray[4] =
{
BYTE_ARRAY(x)
};
}
This compiles and runs, but generates the wrong result. I thought the preprocessor did a direct substitution of the macro into the code, so I would have expected that this would return exactly the same compiled binary. What am I missing? Alternatively, is there a 'better' way to accomplish this without using a macro?