0

I have this code that write and write from EEPROM for 4 digit number. For Ex: 2356

Code;

void WritePassToEEPROM(uint16_t pass)
{
   EEPROMWrite(0000,(pass%100));
   EEPROMWrite(0001,(pass/100));
}

uint16_t ReadPassFromEEPROM()
{
   return (EEPROMRead(0001)*100  +  EEPROMRead(0000));
}

The Write_Pass_To_EEPROM() function writes to 2 addresses 0000 and 0001. for 2356, 2356%100 is 56 and 2356/100 is 23. So, at address 0000 it will be 56 and at address 0001 it will be 23. While reading EEPROM_Read(0000) will return 34 and EEPROM_Read(0001)*100 will return 2300. 2300 + 56 is 2356.

But if i need to write 5 digit number like 65238 what should i do.

Embedded C
  • 1,448
  • 3
  • 16
  • 29
  • 2
    Why would you waste 61% of each byte like that? – Ignacio Vazquez-Abrams Mar 26 '16 at 07:51
  • 1
    Why use *decimal* arithmetic? You do know that 16 bits (two bytes) as an unsigned integer can contain values between `0` and `65535` (inclusive). – Some programmer dude Mar 26 '16 at 07:57
  • If he wants to store things such as `99999` (for which 16 bits are too little and 32 are too much), then go 24-bit or something... Or maybe he has to deal with some old crufty hardware/software that works with BCD? – 3442 Mar 26 '16 at 07:58

1 Answers1

0

This will go up to 0xffff (65535).

void WritePassToEEPROM(uint16_t pass)
{
   EEPROMWrite(0000,(pass & 0x00ff));
   EEPROMWrite(0001,(pass & 0xff00) >> 8);
}

uint16_t ReadPassFromEEPROM()
{
   return ((uint16_t)(EEPROMRead(0001) << 8)  +  (uint16_t)EEPROMRead(0000));
}
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124