Search code examples
cgdbuint

uint32_t has 28 bits instead of 32 bits


I've encountered a confusing situation. I have this simple addition inside my code:

temp = thi + t2lo;

I have defined thi and t2lo as uint32_t in my code and temp as uint64_t:

uint32_t thi, tlo, t2hi, t2lo;
uint64_t temp = 0;

My code doesn't work properly, so I use gdb to figure out what is going wrong. When I tried to print variables in gdb I've got:

(gdb) p/x temp
$1 = 0xfeffff2
(gdb) p/x thi
$2 = 0xff00000
(gdb) p/x t2lo
$3 = 0xfffffff2

As you can see here, thi has 28 bits instead of 32 bits, and the addition result is completely wrong. Could anyone tell me what is going on here?

PS: I have a large code and I cannot put my whole source code here for you guys to reproduce this situation. Also, this situation only occurs for certain inputs and most of the time my code is working correct. I just want to check with you guys if you encountered something like this before. Any help would be greatly appreciated.


Solution

  • The size of uint32_t is 32 bits, not 28.

    What happens here is that the most significant 4 bits are 0, and the leading zeros are not printed by gdb with p/x.

    0xff00000 is the same as 0x0ff00000.

    Use p/z thi to include the leading zeros when displaying. Have a look here: https://sourceware.org/gdb/onlinedocs/gdb/Output-Formats.html