What do these macros do?

I inherited some very confusing and poorly written PIC code to modify. There are two macros here:

#define TopByteInt(v) (*(((unsigned char *)(&v)+1))) #define BottomByteInt(v) (*((unsigned char *)(&v))) 

Can anyone explain what they are doing and what it means?

Thanks:)

+5
source share
3 answers
 (*((unsigned char *)(&v))) 

It passes v (16-bit integer) to char (8 bits), doing this, you get only the bottom byte.

 (*(((unsigned char *)(&v)+1))) 

This is the same, but it gets the address v and the sum is 1 byte, so it only gets the top byte.

It will work as expected if v is an integer of 16 bits.

+1
source

They access a 16-bit integer variable one byte at a time, providing access to the most significant and least significant byte halves. Low byte order is assumed.

Usage will be as follows:

 uint16_t v = 0xcafe; const uint8_t v_high = TopByteInt(&v); const uint8_t v_low = BottomByteInt(&v); 

The above will cause v_high be 0xca and v_low equal to v_low .

This is pretty scary code, it would be easier to just do it arithmetically:

 #define TopByteInt(v) (((v) >> 8) & 0xff) #define BottomByteInt(v) ((v) & 0xff) 
+5
source

Ugg.

Assuming you are on a little-endian platform, it looks like this could be meaningfully written as

 #define TopByteInt(v) (((v) >> 8) & 0xff) #define BottomByteInt(v) ((v) & 0xff) 

It basically takes the variable v and extracts the least significant byte ( BottomByteInt ) and the next more significant byte ( TopByteInt ) from it. "TopByte" is a little wrong if v is not a 16-bit value.

+1
source

Source: https://habr.com/ru/post/1201147/


All Articles