Shammer's Philosophy

My private adversaria

16進数を2進数で表示させる

C言語で2進数を表示させる・改 - Shammerismで言及した関数を書いた。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_as_b_value(const long value){
  unsigned long bit = (1L << (sizeof(long) * 8 - 1));
  int i = 0;
  int x = 0;
  for( ; bit != 0 ; bit >>= 1, ++i ){
    if( i != 0 && i % 4 == 0 && x ){
      putchar('.');
    }
    if( value & bit ){
      putchar('1');
      x = 1;
    }
    else {
      if ( x ) putchar('0');
    }
  }
  printf("\n");
}

char* reverse_string(char* value){
  if ( strlen(value) < 2 ) {
    return value;
  }
  else {
    char *result = malloc(strlen(value) - 1);
    int i, j;
    for( i = 0, j = strlen(value) - 1 ; i < strlen(value) ; i++, j-- ){
      result[i] = value[j];
    }
    result[i] = '\0';
    return (char *)result;
  }
}

long hex_to_decimal(char *value){
  int i = 0;
  int n;
  int base = 1;
  long result = 0;
  char c;
  while( value[i] != '\0' ){
    if ( '0' <= value[i] && value[i] <= '9' ){
      n = value[i] - '0';
    }
    else if ( 'a' <= (c = tolower(value[i])) && c <= 'f') {
      // a 
      n = c - 'a' + 10;
    }
    else {
      printf("Detected invalid character: %c\n", value[i]);
      exit(1);
    }
    i++;
    result = result + base * n;
    base = base * 16;
  }
  return result;
}

void hex_to_ascii(char *value){
  long x = hex_to_decimal(reverse_string(value));
  print_as_b_value(x);
}

int main(int argc, char *argv[]){
  if ( argc != 2 ){
    printf("Usage: %s value\n", argv[0]);
    return 1;
  }
  hex_to_ascii(argv[1]);
  return 0;
}

実行結果は以下。一応、期待通りになっているように見える。

# ./a.out 1
1
# ./a.out 2
10
# ./a.out 3
11
# ./a.out 4
100
# ./a.out 5
101
# ./a.out 6
110
# ./a.out 7
111
# ./a.out 8
1000
# ./a.out 9
1001
# ./a.out a 
1010
# ./a.out b
1011
# ./a.out c
1100
# ./a.out d
1101
# ./a.out e
1110
# ./a.out f
1111
# ./a.out 10
1.0000
# ./a.out 11
1.0001
#