Casting a long to an int[]

Heya! I'm trying to make a calculator for a school project, but I've got a problem. The code I've got for the display requires an array of integers, but the code for the calculations returns a long. Here's the code I've got right now, but for some reason it breaks after a few cycles, returning negative numbers for no discernible reason, making it so that input_array = { -2, -3, 0, -1, 3, 0, 0, 8 }. I've included the important parts of the code below, if anything else is important, I can give that as well.
I've got two important questions:

  1. Why does this break?
  2. How do I make it so it doesn't?
    Also, if there's a better way to cast this, that would be nice to know as well! :slight_smile:
// Display
long input_number;
int input_array[8];
float result;

void setup() {

}

void loop() {
  if (!solved) {
    // Result is set based on calculations via a keypad

    input_number = abs(round(result));
    solved = true;

    Serial.println(input_number);

    // Preparing the display
    if (!is_error) {
      for (i = 0; i < 8; i++) {
        input_array[i] = (int(input_number / pow(10, i))) % 10;
        // It breaks here
      }
    }
  }


  // Display based on input_array
}

Welcome to the forum
Thank you for using code tags in your first post. Many don't

Please post your full sketch

long input_number = 12345678;
byte input_array[8] = {0};

void setup() {
  Serial.begin(115200);
  Serial.println(input_number);
  for (byte i = 0; i < 8; i++) {
    long Temp = input_number  / pow(10, i) ;
    input_array[i] = Temp% 10 ;
    Serial.print(input_array[i]);
  }
  Serial.println();
}

void loop() {
}

Why do you store Temp%10 in your array instead of Temp?

just another way of doing it :wink:

long input_number = 12345678;
byte input_array[8] = {0};

void setup() {
  Serial.begin(115200);
  Serial.println(input_number);

  char temp[10];
  sprintf(temp,"%ld",input_number);
  
  for(int i=0;i<8;++i){
    input_array[i] = temp[i]&0x0F;
    Serial.print(input_array[i]);
  }

  Serial.println();
}

void loop() {
}

hope that helps...

@build_1971 he wants an array with decimal digits of the long number.
@sherzaad &0x0F it will then hexadecimal

No.
Here is why not:

i don't liked pow() anyway

long input_number = 90345678;
byte input_array[8] = {0};

void setup() {
  Serial.begin(115200);
  Serial.println(input_number);
  long Temp = input_number   ;
  for (byte i = 0; i < 8; i++) {
    input_array[7-i] = Temp % 10 ;
    Temp /= 10 ;
    Serial.print(input_array[i-7]);
  }
  Serial.println();
}

void loop() {
}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.