Preprocessor division giving weird value

0

This is driving me crazy. I have a code which is outputting a weird value while using division:

#define NANOSECONDS_PER_SECOND   1000000000
uint64 CurrentTimeInNanoSecs; 

    uint64 GetTimeInNanoSecs( )
   {
      printf("\n%X", (CurrentTimeInNanoSecs >> 32) ); 
      printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF) ); 
      return ( CurrentTimeInNanoSecs );
   }

void GetCurrentTimeInSecs()
{
  uint32 Time = GetTimeInNanoSecs() / NANOSECONDS_PER_SECOND;
  printf("%X", time);
}

void main()
{
GetCurrentTimeInSecs();
}

On init, I see the prints as follows: 0x00000000 0x3016DC6B 0x00000198

I am not sure what is happening. Can someone pls help.

c
c-preprocessor
integer-division
unsigned-integer
asked on Stack Overflow Sep 7, 2020 by user8664114 • edited Sep 7, 2020 by user8664114

2 Answers

0

Beware that printf format specifiers must agree with the datatype that is passed, otherwise data may be misinterpreted and print as gibberish!

The correct way to print a uint64_t is with printf("%" PRIu64 "\n", x);, where PRIu64 is defined in inttypes.h. Note: Pre-C11, you may need to define __STDC_FORMAT_MACROS to get PRIu64, as described in this SO post.

More generally, see the table in https://en.cppreference.com/w/cpp/io/c/fprintf of the expected types for each specifier. There's also a good printf format string article on Wikipedia about it.

I recommend compiling with warnings turned on. Use command line option -Wall, if using clang or gcc. Most compilers should give warnings on the posted code like:
format '%X' expects argument of type 'unsigned int', but argument has type 'uint64_t'

answered on Stack Overflow Sep 7, 2020 by Pascal Getreuer
0

My bad: I know I posted the code as:

printf("\n%X", (CurrentTimeInNanoSecs >> 32) );

but in reality I wrote it as:

printf("\n%X", (CurrentTimeInNanoSecs & 0xFFFFFFFF >> 32) );

So my upper 32 bits were always zero and I was misinterpreting the results :/

Thank you to the community though.

answered on Stack Overflow Sep 7, 2020 by user8664114

User contributions licensed under CC BY-SA 3.0