Hatena::Groupcprogramming

てーげーC言語

2009-02-12

3-5

| 02:40

数値を文字に変える演算がいつもスッと出てこない!

#include <stdio.h>

void reverse(char *s) 
{
  int i, j;
  char temp, *p; 

  i = j = 0;
  p = s;
  

  while(*p++) {
    i++;
  }   

  while(--i > j) {
    temp = *(s+i);
    *(s+i) = *(s+j);
    *(s+j) = temp;
    i--;
    j++;
  }
}

void itob(int n, char* s, int b)  
{
  int d;
  char *p; 

  p = s;

  do {
   *p++ = (d = n % b) <= 9 ? d +'0' : d - 10 + 'a';
  } while((n/=b) != 0); 

  *p = '\0'; 

  reverse(s);
}

int main()
{
  char s[128];
  int n;

  n = 15;

  itob(n, s, 8);
  printf("%s\n", s);

  itob(n, s, 16);
  printf("%s\n", s);

  return 0;
}
# ./a.out                
17
f