3

I'm having following structure

struct data {
    uint64_t addr:50;
};

If i want to print the value of addr in hexa decimal format which format specifier should i use ?

Chinna
  • 3,930
  • 4
  • 25
  • 55
  • any problems using `%x` specifier? however, it'll not give you _exact_ value for `bitfield` variables. it'll consider the `datatype`. maybe you can use a `mask` to filter the required bits before printing. – Sourav Ghosh Dec 09 '14 at 07:43
  • There is no format specifier for 50 bit values. You have to do it by yourself. – Jabberwocky Dec 09 '14 at 07:43
  • 1
    Or... don't use a bit field at all, use an uint64_t. Please note that bit fields cannot be reliably used for _anything_ but as a container for a chunk of boolean flags. For example, [see this](http://stackoverflow.com/questions/6043483/why-bit-endianness-is-an-issue-in-bitfields/6044223#6044223). – Lundin Dec 09 '14 at 07:52

1 Answers1

1

You should do it in two steps: first, create a full uint64_t variable with a copy of addr, then print it using "%" PRIx64.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
  • 4
    No, you can't assume that `unsigned long` (the type `%lx` expects) is `uint64_t`. The proper way to print `uint64_t` is using `"%" PRIx64`. – unwind Dec 09 '14 at 07:56
  • Great. I'll leave my comment since it's mildly informative even though the code I referred to is no longer around. – unwind Dec 09 '14 at 08:36
  • Why not print it directly with the `"%" PRIx64` specifier? The bit field is of type `uint64_t` as we can see with `static_assert`... Why do you need a copy first? The only problem I have noticed is that _if_ the bit field is small enough to fit into lower type (like 32 bits or less, that would fit into `unsigned int`) then Clang with `-Wformat` emits a warning that `%lu` is used when `%u` should be. Unfortunately, using `%u` makes the opposite warning on GCC. I ended up using explicit `static_cast` in the `printf`. Interestingly, this does not trigger `-Wuseless-cast` in GCC... – Adam Badura Mar 05 '22 at 08:19
  • @AdamBadura: You ask why make a copy, then you say you use `static_cast`. That's making a copy. Which is fine of course, it's not like this copy is slow compared with the formatting. – John Zwinck Mar 05 '22 at 09:25
  • @JohnZwinck, I realized that myself after I wrote the comment... :) But there is more into this. The `static_cast` we have is only to silence Clang (`-Wformat`) that apparently notices the bit fields is "too small" and treats it as `unsigned int` instead of `uint64_t` (that happens to be `unsigned long` in our case). GCC doesn't emit such warning and we could (I guess?) get away without the `static_cast`. – Adam Badura Mar 06 '22 at 13:28