C: How to save the result of 2 32-bit unsigned integer to unsigned integer

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- ?
+4
2

, C x = y + z; , y + z, x. , , .

, peak_seq - pkt_seq, , . uint32_t ( int, , 32 ), uint32_t. uint32_t.

, 4294967295. , peak_seq - pkt_seq (uint32_t)4294967295, 0xFFFFFFFF.

64- 4294967295, -1?

int32_t, , , 0xFFFFFFFF, -1.

int64_t, .

32- 64- ?

, . , , , , .

, int32_t printf("%" PRId, fig32) int64_t PRId64 (inttypes.h).

+1

C , unsigned int 2 n ( n - int). , peak_seq - pkt_seq unsigned int FFFFFFFF 4294967295. int64_t uint64_t, 4294967295. , int, , ( 2) -1 = > fig32 = -1, .

2 -1. , - .

  • : , , int64_t -
  • : 2 uint32_t int32_t, int64_t. -1 ( int32_t), -1 int64_t
+1

Source: https://habr.com/ru/post/1608311/


All Articles