We are running a survey to help us improve the experience for all of our members. If you see the survey appear, please take the time to tell us about your experience if you can.
How can you access the individual bytes making up a variable of type long? What I need to do is move a 24-bit (3 bytes) unsigned char array into a long variable. An example:
unsigned char a[3]; unsigned long b; a[0] = 0x02; a[1] = 0xFF; a[2] = 0xFF; ????? ?????
I run into this problem in a few places in my code. A union/array is much faster with Keil C51 than shifting. The code generated takes the shift very literally, and ripples one bit through the carry all the way through your U32, n times. (I've wished for strength reduction on multiples of 8 in the shifts.) Those shifts by 24 to get to the high byte are death to speed, and the library calls to the U32 shift function takes up space, too. The union/array approach usually generates a nice direct access to the proper byte or register.
typedef union { U16 u16; U8 array[2]; #if defined(CPU_ENDIAN_BIG) struct { U8 msb; U8 lsb; } bytes; #elif defined(CPU_ENDIAN_LITTLE) struct { U8 lsb; U8 msb; } bytes; #else #error Must define CPU_ENDIAN_BIG or _LITTLE #endif } MultiByte16;