Issue / bad logic in EEPROM example

I was looking through the example code for the EEPROM library, and noticed this mistake:

/***
Need to divide by 4 because analog inputs range from
0 to 1023 and each byte of the EEPROM can only hold a
value from 0 to 255.
***/

int val = analogRead(0) / 4;

Whoever wrote the above doesn't seem to realize that dividing by 4 is NOT the right approach to storing a number than can range from 0 to 1023. Basically what we have here is a number that should take no more than 10 bits to store (2 ^ 10 = 1024). So, dividing by 4 isn't really what we want. Instead, I would suggest using the highByte() / lowByte() functions, as that will split the word into two separate bytes. By definition a word (2 bytes) can store a unsigned number in the range 0 to 65535 (one less than 2 ^ 16).

I'm just sayin'...

Dan

Upon further reflection, I suppose that the way the code in the example is written is not so bad, assuming that you don't care to store all 10 bits. Dividing by 4 will have the effect of just discarding the lower 2 bits and storing the most significant 8 bits. Which may be fine for most folks. But if you want to store all 10 bits, then I recommend using the highByte() and lowByte(), as I said.

Dan

A few things...

Thank you for the follow-up.

Excellent observation and write-up.

Do not run sock puppets.