0

I have a simple question.If I wanted top add some hex values in vc++ like 0x140000000 and 0x02F61570 my calculator says the result is 0x142f61570, but in my code ,if I add these two numbers I only get 0x42f61570. Where could the problem be ?

I have already tried with maybe some other values than storing the hex in DWORD ,but the result is the same.

DWORD base = 0x140000000;
DWORD address = 0x02F61570;
DWORD next = base + address;
printf("0x%x\n",next);

the result of the operation in my code are => 0x42f61570 as opposed to my calculator ,which says 0x142f61570

  • Have you tried `DWORD sum = 0x142f61570;` ? What happens? – Ben Voigt Jun 16 '19 at 19:49
  • @DaveS: No.... the prefix for hexadecimal is `0x` not `0x0`. And octal literals never contain an `x` – Ben Voigt Jun 16 '19 at 19:51
  • Ah, thanks -- I never use octal so I'm probably thinking of something ancient like Turbo C++ for DOS :) – Dave S Jun 16 '19 at 19:52
  • @DaveS: I don't think Turbo C++ is old enough to get octal vs hexadecimal literals wrong... those have been that way since C (not ++). – Ben Voigt Jun 16 '19 at 19:53
  • Yep, my brain was just misfiring - https://stackoverflow.com/questions/2670639/why-are-hexadecimal-numbers-prefixed-with-0x – Dave S Jun 16 '19 at 19:57

1 Answers1

0

DWORD is a typedef for a 32-bit unsigned integer, and operations on unsigned integers in C++ are performed using modular arithmetic. printf is showing you the real value of next, and that value is the correct result of base + address when using arithmetic modulo 232.

In fact, the original initialization DWORD base = 0x140000000; already reduced the value modulo 232. Didn't your compiler generate a warning for an out-of-range constant initializer?


The expected output is achieved if you use 64-bit variables.

DWORD64 base = 0x140000000;
DWORD address = 0x02F61570;
DWORD64 next = base + address;
printf("0x%I64x\n", next);
Ben Voigt
  • 277,958
  • 43
  • 419
  • 720