I have the following code snippet that saves the result in a 32-bit integer value and a 64-bit signed integer.
Using a 32-bit signed integer leads to a problem when I subtract 0 with 2147483647 (The maximum allowed value for a 32-bit signed number), so the correct way should be to use a 64-bit signed integer, and I would have to assign an unsigned 32-bit value to a signed 64-bit to get the desired response. Is this right to do?
#include <stdio.h>
#include <string.h>
#include <stdint.h>
int main(void)
{
int32_t fig32;
int64_t fig64;
uint32_t peak_seq = 2480694779;
uint32_t pkt_seq = 2480694780;
uint32_t zero_seq = 0;
fig32 = peak_seq - pkt_seq;
fig64 = peak_seq - pkt_seq;
printf("\n 32 ans : %d, 64 ans is %ld\n", fig32, fig64);
fig32 = zero_seq - pkt_seq;
fig64 = zero_seq - pkt_seq;
printf("\n 32 ans : %d, 64 ans is %ld\n", fig32, fig64);
fig64 = (int64_t)peak_seq - (int64_t)pkt_seq;
printf("\n fix for (peak - pkt) 64 ans is %ld\n", fig64);
fig64 = (int64_t)zero_seq - (int64_t)pkt_seq;
printf("\n fix for (zero - pkt) 64 ans is %ld\n", fig64);
}
When I run this program, I get the following output
32 ans : -1, 64 ans is 4294967295
32 ans : 1814272516, 64 ans is 1814272516
fix for (peak - pkt) 64 ans is -1
fix for (zero - pkt) 64 ans is -2480694780
- In the first line, why the answer is for 64-bit 4294967295, and not -1?
- 32- 64-
?