2 byte value into 2 separate 1 byte values

Thread Starter

engelbrekt

Joined Apr 21, 2021
10
Hello, I'm currently trying to store 2 values of 2 bytes each to the EEPROM to my PIC16. The EEPROM stores single bytes. How would I divide my value into 2 bytes to write them? And how do I then read them into one single value again? I'm using C.
 

sagor

Joined Mar 10, 2019
903
It also depends on what programming language you use. Some allow equating (mapping) two bytes to a word (high byte/low byte). With that mapping, you create the word value and simply store the byte values that are mapped to that word. Reverse is the same, read the mapped bytes and the word "magically" has the right value.
Other languages allow reading/writing the bytes of a word separately. That is, "word.lb" and "word.hb" would be the respective byte values of "word"
 

dl324

Joined Mar 30, 2015
16,845
Union example:
Code:
union {
  uint16_t wrd;
  unsigned char b[2];
  struct {
    unsigned char b1 : 8;
    unsigned char b0 : 8;
  } byt;
} dat;

int main() {

  dat.wrd = 0xABCD;

  printf("wrd = 0x%X ", dat.wrd);
  printf("b[1] = 0x%X, b[0] = 0x%X ", dat.b[1], dat.b[0]);
  printf("byt.b1 = 0x%X, byt.b0 = 0x%X\n", dat.byt.b1, dat.byt.b0);
  exit(0);
Note that the C standard doesn't specify bit order for bit fields, so you need to experiment with your compiler.
Code:
wrd = 0xABCD b[1] = 0xAB, b[0] = 0xCD byt.b1 = 0xCD, byt.b0 = 0xAB
 
Last edited:
Top