简体   繁体   中英

32 bit addition of two numbers in C

I have a code which performs the 32 bit addition of two numbers.I am generating 10 random 32 bit numbers and each of them are stored in two separate files as their corresponding hex values.The result is also stored in another file in the same way on the execution of the code i am getting some negative values for certain combinations.

Here is my code.


    #include <stdio.h>
    #include <stdint.h>
    #include <stdlib.h>
    #include <time.h>
    #include <string.h>
    #define TARGET_MAX 2147483647L
    void main ()
    {
        int32_t A[10] = {0};
        int32_t B[10] = {0};
        int32_t S[10] = {0};
        int i =0;
        int n =10;
        char hex[32] ={0};
        time_t t;
        FILE *fp = NULL;
        FILE *fp1 = NULL;
        FILE *fp2 = NULL;
        fp = fopen("A.txt","w");
        fp1 = fopen("B.txt","w");
        fp2 = fopen("S.txt","w");
        srand((unsigned) time(&t));
        for(i=0;i<n;i++)
        {
            A[i] = rand() % TARGET_MAX;
            if(fp != NULL)
            {   
                sprintf(hex,"%x",A[i]);
                fprintf(fp,"%s\n",hex);
                memset(hex,0,sizeof(hex));
            }
            B[i] = rand() % TARGET_MAX;
            if(fp1 != NULL)
                    {   sprintf(hex,"%x",B[i]);
                fprintf(fp1,"%s\n",hex);
                memset(hex,0,sizeof(hex));
                    }
            S[i] = A[i] + B[i];
            if(fp2 != NULL)
                    {   sprintf(hex,"%x",S[i]);
                fprintf(fp2,"%s\n",hex);
                memset(hex,0,sizeof(hex));
                    }
            printf(" %d + %d = %d \n\r",A[i],B[i],S[i]);
        }
        fclose(fp);
        fclose(fp1);
        fclose(fp2);
    }

Here is my output


    vu2swz@PPDP01:~/vlsi_lab/exp6$ gcc add.c -o add
    vu2swz@PPDP01:~/vlsi_lab/exp6$ ./add 
     1000086044 + 1204997665 = -2089883587 
     436835310 + 1696128436 = 2132963746 
     1624838244 + 335108562 = 1959946806 
     1782944281 + 1013582119 = -1498440896 
     1491331491 + 1257744454 = -1545891351 
     1676611730 + 773175875 = -1845179691 
     422206991 + 2136514004 = -1736246301 
     1622400103 + 152657712 = 1775057815 
     809410550 + 1662804335 = -1822752411 
     1396954314 + 742609108 = 2139563422 

You're running into overflow.

In the instances where you're getting a negative number, the result is overflowing what can fix in a signed 32 bit integer.

Since the numbers you're generating are smaller than 2 31 , their sum will be less than 2 32 which will fit in an unsigned 32 bit integer. So change your types to uint32_t and use the %u format specifier to print them.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM