write read negative numbers from/to EEPROM

Hi everyone,

when I try to store a negative number in EEPROM I fail:

code:

EEPROM.write(3, -1); // address = 3, value = -1
byte A = EEPROM.read(3);
Serial.println(A, BIN);
Serial.println(A, DEC);

output:

11111111
255

Problem: EEPROM.read does not account for the sign. It treats the byte as unsigned.

One should mention this fact in the reference section.

What is a workaround?

Thanks for your help,

a Newbee.

Description

Write a byte to the EEPROM.

Syntax

EEPROM.write(address, value)

Parameters

address: the location to write to, starting from 0 (int)

value: the value to write, from 0 to 255 (byte)

Problem: EEPROM.read does not account for the sign. It treats the byte as unsigned.

One should mention this fact in the reference section.

The "problem" is not in the read function.

Hi Paul,

thanks, I missed that!

Please read this playground article - Arduino Playground - EEPROMWriteAnything

Hi Rob,

thanks for the link to the EEPROM functions. It seems that also these functions do not support negative numbers.

I solved the problem like this: I write a negative int into EEPROM as two bytes with EEPROM.write and I read and convert it like this:

int counter = 0; // start address
int a = word(EEPROM.read(counter++), EEPROM.read(counter++));
if((a>>15) == 1) a = a - 65535;

More consistent would be perhaps: if(a>32768) a = a - 65535;
or: if((a>>15) == 1) a = - (~a + 1);

This turns an unsigned int into a signed int.

Why not just use a cast?

1 Like

It seems that also these functions do not support negative numbers

You are wrong. They do support negative numbers.

Hi Groove and Coding Badly,

@ CB: I didn't analyze the functions well enough. I will do that.

@ Groove: I tried the signed() function but it didn't work. Which cast could I use?

Nrewbee

Is 'signed' a cast?

'(int)' or '(unsigned int)' certainly are.

Hi Groove,

Is there the cast (signed int) which I would need to convert an unsigned int into a signed int?
Because the variable is already treated as unsigned. How to convert it to a signed int?

'(int)'