Forum Rule: Always post complete source code & details to reproduce any issue!
Results 1 to 3 of 3

Thread: try to multiply two uint32_t into a uint64_t seems not to work

  1. #1
    Senior Member+ Theremingenieur's Avatar
    Join Date
    Feb 2014
    Location
    Colmar, France
    Posts
    2,600

    try to multiply two uint32_t into a uint64_t seems not to work

    I wanted to create a function which multiplies a uint32_t with a uint16_t and with another uint16_t which would give a uint64_t result. That did not work on my Teensy 3.1.
    Printing a uint64_t with Serial.print() gives a compiler error, obviously there is a prototype missing :
    Code:
      Serial.begin(57600);
      delay(1000);
      uint64_t result = (uint32_t)0x6459D01A * (uint16_t)0x803B;
      Serial.print(result);
    does not compile, it says "error: call of overloaded 'print(uint64_t&)' is ambiguous".

    So, I tried to divide my resulting uint64_t up into two uint32_t (upper and lower):
    Code:
       Serial.begin(57600);
      delay(1000);
      uint64_t result = (uint32_t)0x6459D01A * (uint16_t)0x803B;
      uint32_t lower = result & 0xFFFFFFFF;
      uint32_t higher = (uint64_t)result >> 32;
      Serial.print(higher, HEX);
      Serial.print(" + ");
      Serial.print(lower, HEX);
    The result is : "0 + 8BFF5FE". That means that the upper half of the uint64_t is either not calculated or it is truncated.

    What am I doing wrong???

    Thank you in advance for your help!
    Last edited by Theremingenieur; 01-25-2015 at 09:41 PM.

  2. #2
    Senior Member PaulStoffregen's Avatar
    Join Date
    Nov 2012
    Posts
    25,092
    Try this:

    Code:
    uint64_t result = (uint64_t)0x6459D01A * (uint16_t)0x803B;
    The compiler will still implement this as a 32x32 multiply, but at least one of the inputs needs to be cast to 64 bits to prevent the compiler from defaulting to only a 32 bit result. I don't know why assigning the result to a 64 bit variable isn't enough, but apparently it isn't. I know casting one of the inputs to 64 bits works, because I used it in numerous places in the audio lib.

  3. #3
    Senior Member+ Theremingenieur's Avatar
    Join Date
    Feb 2014
    Location
    Colmar, France
    Posts
    2,600
    Yes, that works! Paul, thank you, you are a genius.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •