Convert Unsigned 8 bit integer to a string ?

#3630064
Rate this post
• ▲ useful
▼ not useful
If you use C:
1
  unsigned char number_txt[4], hundred=0, ten=0;
2
  while(1)
3
  {
4
    if(number>=100)
5
    {
6
      number=number-100;
7
      hundred++;
8
    }  
9
    else
10
      break;
11
  }
12
  while(1)
13
  {
14
    if(number>=10)
15
    {
16
      number=number-10;
17
      ten++;
18
    }  
19
    else
20
      break;
21
  }
22
  number_txt[0]=hundred+'0';
23
  number_txt[1]=ten+'0';
24
  number_txt[2]=number+'0';
25
  number_txt[3]=0x00;
Guest #3630151
Rate this post
• ▲ useful
▼ not useful
Why this construct with while(1)/if?

This is simpler:
1
  unsigned char number_txt[4], hundred=0, ten=0;
2
  while (number >= 100)
3
  {
4
    number = number-100;
5
    hundred++;
6
  }
7
  while (number >= 10)
8
  {
9
    number = number-10;
10
    ten++;
11
  }
12
  number_txt[0] = hundred+'0';
13
  number_txt[1] = ten+'0';
14
  number_txt[2] = number+'0';
15
  number_txt[3] = 0;

or still shorter:
1
  unsigned char number_txt[4], hundred=0, ten=0;
2
  while (number >= 100)
3
  {
4
    number -= 100;
5
    hundred++;
6
  }
7
  while (number >= 10)
8
  {
9
    number -= 10;
10
    ten++;
11
  }
12
  number_txt[0] = hundred+'0';
13
  number_txt[1] = ten+'0';
14
  number_txt[2] = number+'0';
15
  number_txt[3] = 0;

Reply

Note: the original post is older than 6 months. Please don't ask any new questions in this thread, but start a new one.

Formatting
  • [c]C-Code[/c]
  • [code]code in other languages, ASCII drawings[/code]
  • [math]formula (LaTeX syntax)[/math]
  • [[Title]] – link to an article
  • Link to another post: right-click its post ID (#8078628), copy the address, paste it into the text

More about formatting

Post long source code as an attachment, not in the text.

Already registered? Log in

Not shown to anyone. We send you a link; your post appears once you confirm it there.

By submitting you create a free account and accept the terms of use.