-3

I'm trying to use atoi() but I need the 0 in the front, but the function ignores it

  sprintf(str, "%d%d%d%d",comp[cont][0],comp[cont][1],comp[cont][2],comp[cont][3]);
  conv=atoi(str);  

  printf("%d \n",conv);  

When I print str: 0100
And conv: 100
Is there any way to show the 0?

Lkopo
  • 4,798
  • 8
  • 35
  • 60
  • 1
    You can try using `printf` with a leading zero. http://stackoverflow.com/questions/153890/printing-leading-0s-in-c – austin Dec 28 '13 at 16:39
  • 3
    The leading zero is not part of the *value*, it's part of the *representation*. – Oliver Charlesworth Dec 28 '13 at 16:39
  • In C a leading `0` indicates the octal representation of an integer value: `020==0x10=16`. Binary valued I'd prefix with a `0b`. – alk Dec 28 '13 at 17:01
  • `str` has a leading 0 if and only if `comp[cont][0]` is 0, so you want to print `conv` with a leading 0 if and only if `comp[cont][0]` was 0 at the time `str` was created but you do not want to output `str` itself? And, if yes, why? – mafso Dec 28 '13 at 17:07
  • str is a char, I needed it to concatenate the 4 int, them using atoi() I converted it into an int again because I need to convert the binary to decimal – user3075022 Dec 28 '13 at 17:13

4 Answers4

6

It's because integers simply doesn't have zeros in front of them.

You need to print it with that:

printf("%04d \n",conv);

You might find e.g. this printf reference useful.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • I know they dont, but it's a binary number and I need the zero to convert it to decimal and write it on a txt. It worked, thanks! – user3075022 Dec 28 '13 at 16:44
3

Just change the printf format:

printf("%04d \n",conv);  
James M
  • 18,506
  • 3
  • 48
  • 56
1

Just append the zero while printing. Try the following

print("0%d\n", conv);
doptimusprime
  • 9,115
  • 6
  • 52
  • 90
0

Why so complicated and not just do directly:

printf("%d%d%d%d", comp[cont][0], comp[cont][1], comp[cont][2], comp[cont][3]);
alk
  • 69,737
  • 10
  • 105
  • 255