I have the following piece of code which saves the result in 32 bit signed integer and 64 bit signed integer.
Using 32 bit signed integer results in a problem when I subtract 0 with 2147483647 (Max allowed value for signed 32 bit integer) so correct way should be using 64 bit signed integer and I should have to typecast unsigned 32 bit to signed 64 bit to get the desired answer. Is this the right way to do it?
#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 is the answer for 64 bit a 4294967295 and not -1 ?
- Is typecasting all the unsigned 32 bit integers to signed 64 bit the only way to solve this problem?
UINT32_MAXfrom<stdint.h>...int64_tcan represent all values ofuint32_t."%"PRIu32and"%"PRId64from<inttypes.h>to printuint32_tandint64_tvalues usingprintf, respectively.longisn't necessarily a 64-bit type. And if both operands are of a 32-bit type then the operation is always done in a 32-bit type. Thereforepeak_seq - pkt_seqis similar to(int64_t)(peak_seq - pkt_seq). If you want to do in higher precision, cast it before doing the operation