How to print a guint64 value when using glib?
Asked Answered
W

1

8

Problem

I am making use of the GLib 2.0 library, and declared a gunit64 variable. I wish to print its value to screen, but its not working properly.

Code

Consider the following code snippet as an example. I declare a guint64 variable, and try to print its value.

guint64 myValue = 24324823479324;
printf("My Value: %d\n", myValue);

Warning

I get this warning:

warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘guint64’ 

Output

I get a strange negative number on screen:

My Value: -1871285220

Further Comments

I tried to search the API's documentation, and I found the following under guint64:

An unsigned integer guaranteed to be 64 bits on all platforms. Values of this type can range from 0 to G_MAXUINT64 (= 18,446,744,073,709,551,615).

To print or scan values of this type, use G_GINT64_MODIFIER and/or G_GUINT64_FORMAT.

Therefore, I assume I have to use either the modifier or format definitions. However, the documentation does not show how to use them. Can anybody help me please?

Waisted answered 7/3, 2013 at 13:53 Comment(0)
W
15

You've found the proper macro for this. Here's how to use it:

printf("My value: %" G_GUINT64_FORMAT "\n", myValue);

Note that the macro is a quoted string literal, so the above is the proper syntax. Also note that the % is not part of the macro.

Your number appears negative since you're using %d, which expects an int, and the bits of your number, when viewed as a smaller, signed int, encode something negative.

Wane answered 7/3, 2013 at 13:56 Comment(4)
@Waisted Maybe stdout just isn't getting flushed due to missing newline? Try printf("My value: %" G_GUINT64_FORMAT "\n", myValue); instead.Diez
@Waisted It would be interesting to learn exactly how your code looks, there might be something silly (like a missing newline as Ancurio says). This really should work, and is the right way to do it.Wane
@Ancurio, I think it was a flushing problem. I added the "\n" and it works.Waisted
@Wane Thank you, it works now. Sorry I didnt give you the correct answer. It did not work for me initially. My bad.Waisted

© 2022 - 2024 — McMap. All rights reserved.