I'm working on a memory address based problem and I found this is very confusing (Below algorithm is mainly calculate the address difference between "Value" and "nv_var.EEStart"):
ValueI = (int*)(Value); // ValueI is int*
EP = (int)(&nv_var.EEStart); // EP is int
E = (long)(EP); // E is long
V = (long)(ValueI); // V is long
adr = (V - E) / 2L; // adr is long
printf("Current V: %.8x\n", V);
printf("Current E: %.8x\n", E);
printf("V-E is: %.8x\n", (V - E));
printf("V-E/2L is: %.8x\n", (V - E) / 2L);
printf("address is %.8x\n", adr);
Then I got the following output:
Current V: 00439488
Current E: 004391e0
V-E is: 000002a8
V-E/2L is: 80000154
address is 80000154
Modbuss address:-2147474308
What confused me is my V-E is actually the expected result, but when I divide this number by 2, the result should be 0x00000154, but I got 0x80000154. I'm using gcc compiler without any extra flag, and the expected result should be 0x154.
I can improve it easily by masking off the MSB, but I just wondering why this will happen.
Thanks for all the help.
E, V, adr is long
, use%.8lx
, ` and enable all warnings.V = (long)(ValueI)
is suspcious. I'd expectV = *ValueI