hey,
I'm pretty new to Arduino and got a question about converting a int into bytes beacause I want to send some Information over I2C. I read that the I2C_anything lib can make that happen or you split it into 2 Bytes.
But is there a way to convert every single digit of an int number into a byte, so I can send every digit alone?
e.g. the number 457 splits into 3 Bytes. Byte 1=4, Byte 2=5 and Byte 3=7.
But is there a way to convert every single digit of an int number into a byte, so I can send every digit alone?
e.g. the number 457 splits into 3 Bytes. Byte 1=4, Byte 2=5 and Byte 3=7.
itoa() will convert an int to an array of chars. A char and a byte are the same size.
Here's a chunk of code I am working on that will convert anything into an array of bytes:
template <class T> void CopyAnything( const T& Source, T& Destination) {
int i;
const byte* _Source = (const byte*)(const void*)&Source;
byte* _Destination = (const byte*)(const void*)&Destination;
for (i = 0; i < sizeof(Source); i++) {
_Destination[i] = _Source[i];
}
}
template <class T> void writeData( const T& Source) {
int i;
byte X;
const byte* _Source = (const byte*)(const void*)&Source;
for (i = 0; i < sizeof(Source); i++) {
X = _Source[i]; // << X represents the destination for the array of bytes to be copied to
}
}
template <class T> void readData( const T& Destination) {
int i;
byte X;
byte* _Destination = (const byte*)(const void*)&Destination;
for (i = 0; i < sizeof(Source); i++) {
_Destination[i] = X; // << X represents the data in bytes you wish to insert into the object
}
}
Kritzl:
But is there a way to convert every single digit of an int number into a byte, so I can send every digit alone?
e.g. the number 457 splits into 3 Bytes. Byte 1=4, Byte 2=5 and Byte 3=7.
Typically, you would not send an int as a series of bytes to be interpreted as a decimal number. An int is two bytes, so usually you'd send the top (or the bottom) 8 bits first and then send the other 8 bits.
Do do this, you use the C++ "bit filddling" operators, which are <<, >>, >>>, &, |, ^, and ~.
to send:
int theValue;
send((byte) (theValue>>8));
send((byte) (theValue));