segler
December 18, 2010, 12:06pm
1
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.
system
December 18, 2010, 12:11pm
2
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.
segler
December 19, 2010, 9:53am
5
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.
It seems that also these functions do not support negative numbers
You are wrong. They do support negative numbers.
segler
December 19, 2010, 6:55pm
8
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.
segler
December 21, 2010, 9:46am
10
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?