Store & Read negative number in EEProm

Hi someone know a way to store and read negative numbers from EEProm than this?

I check if the number is less than 0

then i make a flag in position 0x08,
if 0x08 is=1 then the number is negative.
if 0x08 is=0 then the number is positive.
Then i multiply the number x (-1) this operation convert -65 to 65 and then i write the number in position 0x06 but with a flag in position 0x08 that indicates that CError is negative.

And for read, first i check the flag if is 1.
then i read the number that is stored in eeprom as positive & multiply the number again by (-1) that convert again in negative after read 0x06 position.
but this spend some memory, is not much but im sure that spend much more memory than some correct, official, or whatever the hell it's called.

signed int CError = -65;

//===========write to EEprom negative number

if (CError < 0){
  CError=CError * (-1);
EEPROM.write(0x08,0x01);
delay(50);   
}
else EEPROM.write(0x08,0x00);
EEPROM.write(0x06, CError);


//===========Read from EEProm negative number

if (EEPROM.read(0x08)==1){
delay(50);
CError=EEPROM.read(0x06)*(-1);    
}
else CError=EEPROM.read(0x06);

Have a look at the put() and get() methods.

Use a signed int as the data type for the variable and then save it using EEPROM.put()

Load it back to a signed int variable using EEPROM.get()

Note that it takes 2 bytes of EEPROM to hold an int variable on most, but not all, Arduinos so that 2 ints cannot be saved in adjoining EEPROM addresses

I checked it but if i remember well, just work with negative number, when the number is positive is flaged as negative and i need to store a variable from -100 to 100

the EEPROM just stores bytes. You transform those bytes into what you want when you bring those byte into memory and typed variables

-100 to 100 fits on 1 byte as a int8_t type (-128 to +127 range)

Checked what ?

Ok, can you make me a code example plz?

signed char c {-50};  // Or int8_t.
EEPROM.put(0, c);

signed char d;  // Or int8_t.
EEPROM.get(0, d);
Serial.println(d);

Output:

-50
1 Like

Add 100 to the value before you EEPROM.write() it to ensure that it is positive then, when you EEPROM.read() it subtract 100 to get back the original value

For example :
The value is -100
Add 100 and you get 0
Save the value of 0
Read back the value and get 0
Subtract 100 and you get -100, which is the original value

1 Like

Ok i understand, but is+/- same to the way that i use.

Thank you this is that i need.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.