Joel Coding Problem itoa_radix

mohadang·2023년 4월 16일
0

Coding Problem

목록 보기
5/7
post-thumbnail
#include <stdio.h>
#include <string.h>
#include <assert.h>

void itoa_radix(int val, char buf[], int buf_len, const int radix) {
  memset(buf, 0x0, buf_len * sizeof(char));
  int i = 0;
  while (val > 0) {
    int d = val % radix;
    if (d > 9) {
      buf[i] = 'a' + (d - 10);
    } else {
      buf[i] = '0' + d;
    }
    val /= radix;
    i++;
  }
  // reverse string
  int end_i = i - 1;
  for (int start_i = 0; start_i < end_i; start_i++, end_i--) {
    int temp  = buf[end_i];
    buf[end_i] = buf[start_i];
    buf[start_i] = temp;
  }
}

int main(){
  char buf[12] = "";

  int val = 30;  
  itoa_radix(val, buf, sizeof(buf), 10);
  assert(strcmp(buf, "30") == 0);
  itoa_radix(val, buf, sizeof(buf), 16);
  assert(strcmp(buf, "1e") == 0);
  itoa_radix(val, buf, sizeof(buf), 8);
  assert(strcmp(buf, "36") == 0);  

  val = 1777;
  itoa_radix(val, buf, sizeof(buf), 10);
  assert(strcmp(buf, "1777") == 0);
  itoa_radix(val, buf, sizeof(buf), 16);
  assert(strcmp(buf, "6f1") == 0);
  itoa_radix(val, buf, sizeof(buf), 8);
  assert(strcmp(buf, "3361") == 0);  

  return 0;
}
profile
mohadang

0개의 댓글