Menu

#202 How Multiply Big numbers ? [STM8]

open
nobody
long (1) STM8 (4)
5
2024-12-22
2024-12-15
No

Hi,
My problem is with multiplying large numbers in SDCC.
for example :

void main (void){
  uint32_t a;
  uint64_t b;
  a = 101000;
  b = a * a;
  /* Other Codes ... */
  }

When I read the value of the variable "b" after the above code, I get the incorrect value 1611065408 .
Correct value of Multiply 101000 in 101000 is 10,201,000,000
What is the cause of the problem and its solution?

Discussion

  • Philipp Klaus Krause

    This is not specific to SDCC or the STM8.

    a * a is of type uint32_t, so you only get the lowest 32 bits of the result. 10201000000 is bigger than 4294967295, the maxium value for an uint32_t. If you want the result to have 64 bits, you need to cast at least one operand to that width first, e.g. b = (uint64_t)a * a;.

     
    ❤️
    1
    • Hafez Shirmohamadli

      Thanks for Answer,
      I tested above Code with TypeCasting ( before Create the Ticket ) And it did not solve the problem.

       
  • Hafez Shirmohamadli

    Another question that might help solve my problem:
    How can I enable "long long int" support in sprintf (at SDCC)?

     
    • Philipp Klaus Krause

      AFAIK, you currently can't. As a workaround, I suggest printing an unsigned long long as two hexadecimal unsigned long, one for the upper 32 bits, one for the lower 32 bits.

       
      ❤️
      1
  • Hafez Shirmohamadli

    Hi again,
    my Problem is Solved !
    The problem was that I was reading the values of the variables through the "sprintf" function as follows:

    void main (void){
      uint8_t Buffer[50];
      uint32_t a;
      uint64_t b;
      a = 101000;
      b = (uint64_t)a * a;
      sprintf(Buffer,"Value of a : %lu \n and b : %llu",a,b);
      UART_Send_String(Buffer);
      /* Other Codes ... */
     }
    

    And I didn't know that SDCC doesn't support "long long int" format in "sprintf" function.
    Thanks again for your kind support.

     

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.