Electronic – Breaking a 16-bit long int to write into eeprom

atmeldataeeprommicrocontrollerpic

I am writing data to eeprom AT24C16 using PIC microcontroller pic18f4520. Every address of this eeprom can hold 8-bits while I am using long int's to store data that are 16-bit in size. How to break long int into 2 8-bit parts to write them and how to get them back together after reading from eeprom??

Best Answer

In C, you can use bit-shift and masking to extract each byte of a longer number:

lower_8bits = value & 0xff;
upper_8bits = (value >> 8) & 0xff;

And you can 'reassemble' the number from bytes by doing the reverse:

value = (upper_8bits << 8) | lower_8bits;