--- title: 16進数を10進数に変換する author: kazu634 date: 2009-05-12 wordtwit_post_info: - 'O:8:"stdClass":13:{s:6:"manual";b:0;s:11:"tweet_times";i:1;s:5:"delay";i:0;s:7:"enabled";i:1;s:10:"separation";s:2:"60";s:7:"version";s:3:"3.7";s:14:"tweet_template";b:0;s:6:"status";i:2;s:6:"result";a:0:{}s:13:"tweet_counter";i:2;s:13:"tweet_log_ids";a:1:{i:0;i:4589;}s:9:"hash_tags";a:0:{}s:8:"accounts";a:1:{i:0;s:7:"kazu634";}}' categories: - C ---

プログラミング言語C 第2版 ANSI規格準拠』の練習問題で「16進数を10進数に変換する関数をかけ」というものがあったので、現在挑戦中です。とりあえず1-9までの数字だけを処理すればよいのであればこんな感じになった(…って、これは16進数と言わないか。。。):

#include <stdio.h>
/* htoi: 16進数を10進数に変換する */
void htoi(char hex[]);
/* count: char型の配列の要素数をカウントする。*/
/* argv[1]の要素数を知ろうとして「sizeof argv[1] / sizeof argv[1][0]」が必ず4になるのはなぜ? */
int count(char hex[]);
int main(int argc, char *argv[]) {
htoi(argv[1]);
return ;
}
void htoi(char hex[])
{
int i;
int n = ;
// とりあえずa-fのことは考慮しないよ
for (i = (count(hex) - 1); i != -1; i--)
{
if (i == (count(hex) - 1)){
printf("n = %d + %d\n", n, (hex[i] - '0'));
n = n + (hex[i] - '0');
} else {
printf("n = %d + (16 * %d)\n", n, (hex[i] - '0'));
n = n + (16 * (hex[i] - '0'));
}
}
printf("%d\n", n);
}
int count(char hex[])
{
int i;
int num = ;
for (i = ; hex[i] != '\0'; ++i)
{
num++;
}
return num;
}
プログラミング言語C 第2版 ANSI規格準拠

プログラミング言語C 第2版 ANSI規格準拠