-3

I would like to convert an int to a char[4] where each byte in the char[4] contains a decimal value of 2. So in the following example:

int p = 2999999;

Convert p to the array that is identical to k where k is constructed via:

char k[4];
k[0] = 2;
k[1] = 99;
k[2] = 99;
k[3] = 99;

How can I do this in C?

Thanks in advance!

Vis
  • 301
  • 1
  • 10

2 Answers2

5

It's strange problem for me but OK. here's what I would have done:

  1. Copy value of p so that it can be used later (I assume that this conversion doesn't intend to change its value).
  2. Use modulo operation to get 2 last digits
  3. cut down the copy of p to be able to read next two digits.

So complete answer is:

#include <stdio.h>

int main()
{
    int p = 2999999;
    char k[4];
    int p_copy = p;
    int i;
    for(i = 3; i >=0; i--)
    {
            k[i] = p_copy % 100;
            p_copy /= 100;
    }
    for(i = 0; i < 4; i++)
            printf("k[%d]: %d\n",i, k[i]);
    return 0;
}

And for sanity the output:

gonczor@wiktor-papu:~/tmp$ gcc test.c -o test
gonczor@wiktor-papu:~/tmp$ ./test
k[0]: 2
k[1]: 99
k[2]: 99
k[3]: 99
gonczor
  • 3,994
  • 1
  • 21
  • 46
1

for (i =4; i--; k[i] = p % 100, p /= 100);

Mischa
  • 2,240
  • 20
  • 18