I have a problem when trying to convert a 6 digits number into three hexa decimal numbers I'm using an Arduino Nano I already did the following
Thanks you for reading this
Edit : The code, i think it's horrible
void splitAndConvert(int bignumber)
{
int ID6;
int ID7;
int ID8;
String FirstPart;
String SecondPart;
String ThirdPart;
String BigNumberHexa = String(bignumber, HEX);
if (BigNumberHexa.length() <= 2) {
FirstPart = "0";
SecondPart = "0";
ThirdPart = BigNumberHexa;
}
else if (BigNumberHexa.length() < 4) {
FirstPart = "0";
SecondPart = BigNumberHexa.substring(0,BigNumberHexa.length() - 2);
ThirdPart = BigNumberHexa.substring(BigNumberHexa.length() - 2,BigNumberHexa.length());
}
else if (BigNumberHexa.length() < 6) {
FirstPart = BigNumberHexa.substring(0,BigNumberHexa.length()-4);
SecondPart = BigNumberHexa.substring(BigNumberHexa.length() - 4,BigNumberHexa.length() - 2);
ThirdPart = BigNumberHexa.substring(BigNumberHexa.length() - 2,BigNumberHexa.length());
}
else {
}
ID6 = ThirdPart.toInt();
ID7 = SecondPart.toInt();
ID8 = ThirdPart.toInt();
unsigned char DataToSend[8] = {0x00, 0x00, 0x00, 0x00, 0x00, ID6, ID7, ID8};
can.sendMsgBuf(0x001, 0, 8, DataToSend);
}
If I understand what you are trying to archieve, your code should be:
void splitAndConvert(int bignumber)
{
byte ID6 = 0x00; // int has only two bytes on AVR architecture
byte ID7 = (bignumber >> 8) & 0xFF; // shift right by 8 bits and mask (mask is unnecessary if you are assigning it into byte)
byte ID8 = bignumber & 0xFF; // again bitmask is unnecessary, it'll be cut off to fit into the byte anyway
unsigned char DataToSend[8] = {0x00, 0x00, 0x00, 0x00, 0x00, ID6, ID7, ID8};
can.sendMsgBuf(0x001, 0, 8, DataToSend);
}
And if you really want to have bigger numbers:
void splitAndConvert(int32_t bignumber)
{
byte ID6 = bignumber >> 16; // shift right by 16b, ommited unnecessary mask
byte ID7 = bignumber >> 8; // shift right by 8b
byte ID8 = bignumber; // LSB will be assigned (but with ints you'll have to use bitmasking)
unsigned char DataToSend[8] = {0x00, 0x00, 0x00, 0x00, 0x00, ID6, ID7, ID8};
can.sendMsgBuf(0x001, 0, 8, DataToSend);
}