Hi! I'm working on a routine for reading data from an eeprom byte per byte.
I'm using the following code in an include file:
template <typename T>
uint8_t read(const uint16_t& address, T& value) const {
uint8_t i{0};
uint8_t* bytePtr = (uint8_t*)&value; // Declare pointer to start of structure
for (i = 0; i < sizeof(T); i++) { // Loop for each byte to be read
*bytePtr++ = ePage[address>>8]->readByte((address + i) & 0xFF);// Read a byte
}
return i;
}
ePage[] is an array of I2C_eeprom.
The function works properly with unsigned numbers. But if i try to read a signed number (an int8_t) the function return in the value field a 4 byte result.
I've tryied using an union instead of the pointers, and do the same thing.
The issue is reproducible here:
inserting the following code:
#include <stdio.h>
#include <stdint.h>
int main(void) {
int8_t value = 1;
uint8_t* bytePtr = (uint8_t*)&value; // Declare pointer to start of structure
printf("Value = %X\r\n",value);
*bytePtr = 0xFA; // Read a byte
printf("Value = %X\r\n",value);
return 0;
}
How is possible that value (that is an 8bit variable) return a 4 byte result? 4bytes maybe are the byte of the pointer (or maybe the 32bit as the mcu have a 32bit architecture), but... why?
And here, the same with unions:
#include <stdio.h>
#include <stdint.h>
int main(void) {
int8_t value = 1;
union {
int8_t v;
char o[sizeof(int8_t)];
} x;
//uint8_t* bytePtr = (uint8_t*)&value; // Declare pointer to start of structure
x.v = value;
printf("Value = %X\r\n",x.v);
x.o[0] = 0xFA; // Read a byte
printf("Value = %X\r\n",x.v);
return 0;
}
The problem is present only with int8_t datatype. If i use int16_t or int32_t all works as it should.
What's going on?
Thanks!