How to return a 16 bit value as 64 bit?

374 views Asked by At
// Returns 64 bit mac timer count value
uint64_t get_timestamp()
{
    uint16_t cnt;
    cnt =   read_counter(); 
    printk ("counter value is 0x%x\n", cnt);
    return cnt;
}

within caller:

uint64_t ts;        
ts =    get_timestamp();
printk ( "returned timestamp is 0x%x \n", ts );

I got the following on screen, What is wrong above?

counter value is 0x000045a5 returned timestamp is 0x00000000

counter value is 0x0000698f returned timestamp is 0x00000000

1

There are 1 answers

0
Andreas Grapentin On

You are seeing this issue becasuse you print out the values incorrectly. there are dedicated printf format macros for the uint*_t types.

from the manpage of <inttypes.h>:

   The fprintf() macros for signed integers are:


          PRIdN        PRIdLEASTN   PRIdFASTN    PRIdMAX      PRIdPTR
          PRIiN        PRIiLEASTN   PRIiFASTN    PRIiMAX      PRIiPTR

   The fprintf() macros for unsigned integers are:


          PRIoN        PRIoLEASTN   PRIoFASTN    PRIoMAX      PRIoPTR
          PRIuN        PRIuLEASTN   PRIuFASTN    PRIuMAX      PRIuPTR
          PRIxN        PRIxLEASTN   PRIxFASTN    PRIxMAX      PRIxPTR
          PRIXN        PRIXLEASTN   PRIXFASTN    PRIXMAX      PRIXPTR

so for example, to print a uint16_t and a uint64_t you could write (untested):

int main (void)
{
  uint16_t a = 13;
  uint64_t b = 37;

  printf("uint16_t: %" PRIx16 ", uint64_t: %" PRIx64 "\n", a, b);

  return 0;
}

you should read man stdint.h and man inttypes.h if you are interested in the details, and what the semantics of the LEAST and FAST types are. very cool stuff.