Home > Enterprise >  How to concatenate four integer values into 1 integer?
How to concatenate four integer values into 1 integer?

Time:10-28

How to concatenate four integer values into 1 integer? For example:

num1 = (some digit 1-9) 8
num2 = 5
num3 = 2
num4 = 6

I would like the output to be 8526. num1-4 are randomly generated.

while (user > 0) {
        int digit = user % 10;
        user /= 10;
        return user;
    }

CodePudding user response:

int numeric_concat(int num1, int num2, int num3, int num4)
{
    num1 = 10*num1   num2; // Num1 is now 86
    num1 = 10*num1   num3; // Num1 is now 867
    num1 = 10*num1   num4; // Num1 is now 8675
    return num1;           // Return value 8675
}

int main(void)
{
    printf("Result %d\n", numeric_concat(8,6,7,5) );
    return 0;
}

Output

Success #stdin #stdout 0s 5392KB
Result 8675

CodePudding user response:

If you were to insist on handling this via strings, you might use sprintf and atoi.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

int main(void) {
    int foo[] = {8, 7, 6, 5};
    char bar[5] = {0};

    sprintf(bar, "%1.1d%1.1d%1.1d%1.1d", foo[0], foo[1], foo[2], foo[3]);

    int baz = atoi(bar);
    
    printf("%d\n", baz);

    return 0;
}

Just using math is a much better choice.

  •  Tags:  
  • c
  • Related