Electronic – Casting integer to character

ceeprompic

I am using PIC18f microcontroller. I have to write a 16 bit integer variables (2 bytes) which was cast into two character variable i.e to write each byte in a consecutive adrressess of EEPROM. By first I have to write a upper byte(8bit data) in the EEPROM. I am unable to get the higher 8 bit of the integer variable by the following code (where I am able to write the lower eight bit of the integer variable ). My code is

void int_EEPROM_putc(unsigned char address, unsigned char data);
unsigned char int_EEPROM_getc(unsigned char address);
unsigned char c;
unsigned int d;
unsigned char* e;
unsigned char f;

void main()
{
d=0xffff;
e=(unsigned char*)&d;
//f=*e
f=*(e+1);
int_EEPROM_putc(0x02,f); 
delay_ms(100);
c=int_EEPROM_getc(0x02); 
while(true)
{
    if(c==255)
    {
    PORTB=~PORTB;
    }
    else
    {
    PORTB=0xff;
    }
}

Best Answer

The most general approach for extracting pieces of an integer value is to shift and mask. So:

d = whatever;
c = d & 0xff; // extract low 8 bits
c = (d >> 8) & 0xff; // extract next 8 bits

If, as here, you know that the value in d is 16 bits, you can make the code for the next 8 bits a little simpler by writing

c = d >> 8; // extract high 8 bits of 16-bit value