Create define for 16-bit variable consisting of two 8-bit

1

I would like to know if there is any way to create a define for a "variable" in C that has 16 bits called PORTAB , so write:

PORTAB = 0xAAFF;

Be equivalent to:

PORTA = 0xAA;
PORTB = 0xFF;

Thank you.

    
asked by anonymous 03.09.2017 / 22:45

2 answers

0
#define PORTA (0xAA)
#define PORTB (0xFF)
#define PORTAB (((PORTA) << 8) | (PORTB))

Or else:

#define JUNTAR_16_BITS(a, b) (((a) << 8) | (b))

#define PORTA (0xAA)
#define PORTB (0xFF)
#define PORTAB JUNTAR_16_BITS(PORTA, PORTB)
    
03.09.2017 / 22:50
0

I suggest that you use two different% s, one for reading and one for writing.

Reading:

#define PORTAB ((unsigned short)(((PORTA) << 8) | (PORTB)))

Recording:

#define PORTAB( value ) do{ unsigned short v = value; PORTA = ((unsigned char*)&v)[1]; PORTB = ((unsigned char*)&v)[0]; }while(0)

Example Usage:

#include <stdio.h>

#define PORTAB ((unsigned short)(((PORTA) << 8) | (PORTB)))

#define SET_PORTAB( value ) do{ unsigned short v = value; PORTA = ((unsigned char*)&v)[1]; PORTB = ((unsigned char*)&v)[0]; }while(0)

int main( void )
{
    /* Gravação */

    PORTA = 0xAA;
    PORTB = 0xFF;

    SET_PORTAB( 0xAAFF );

    /* Leitura */

    printf( "PORTA  = 0x%X\n", PORTA );
    printf( "PORTB  = 0x%X\n", PORTB );
    printf( "PORTAB = 0x%X\n", PORTAB );

    return 0;
}
    
04.09.2017 / 15:40