1

I get data from a sensor in int type but the data range from 0 to 999. I need a simple way for the var to always be the same length. Like if I get 123 I don't need to change it but if it's 43 I need it to be 043. Is there a simple way to do that?

Thanks.

Wasaby
  • 11
  • 1
  • 3
    See http://stackoverflow.com/questions/153890/printing-leading-0s-in-c – SolarBear Nov 17 '16 at 13:22
  • You mean to have the same number of digits every time, i.e. padding with leading zeros eventually. – nbro Nov 17 '16 at 13:22
  • The `int` itself already stores leading zeroes, the printing functions just don't print it out. – Hatted Rooster Nov 17 '16 at 13:22
  • @SolarBear Printing is one thing, I'm not sure if that's what the OP is asking for. – nbro Nov 17 '16 at 13:23
  • I send it using serial from an arduino to a raspberry and since there are multiple sensors I need it to always have the same number of digit to sort it out. – Wasaby Nov 17 '16 at 13:27
  • @Gill Bates what? The int does not store leading zeros at all. It doesn't store any of its numbers actually, it stores bits that triggers a specific value. Ex. 16 would be `00001....0'. Where do you see the leading zeroes like 016? In fact if you count the bits turned off as leading zeroes 16 would be 000016 which is incorrect. – Bauss Nov 17 '16 at 13:29
  • @Baus The bits being turned off signifies the integer's value. The type itself doesn't know anything about it's leading zeroes but the binary representation is most definitely one with leading zeroes. – Hatted Rooster Nov 17 '16 at 13:31

1 Answers1

1

Try with:

 printf("%03d", var);
user3794667384
  • 437
  • 7
  • 23