Skip to content

Instantly share code, notes, and snippets.

@jeremy5189
Created November 23, 2013 03:10
Show Gist options
  • Save jeremy5189/7610287 to your computer and use it in GitHub Desktop.
Save jeremy5189/7610287 to your computer and use it in GitHub Desktop.
/*
* Hexadecimal Converter
* http://oj.sslab.cs.nthu.edu.tw/problems/23
* Authored by Jeremy Yen 2013.11.23
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strlen()
#define N 10
void bin(int i)
{
int j = 0;
if( i != 0 )
{
j = i;
bin( i >> 1 ); // 神奇位移運算
printf("%d", j & 0x01 );
}
}
int main()
{
char str[N];
int arr[N];
// 讀入
while(fgets(str, N, stdin))
{
int i, len = strlen(str); // 取字串長度
for( i = 0; i < len - 1; i++ )
{
int temp = (int)str[i];
if( temp >= 48 && temp <= 57 ) // 數字
arr[i] = (int)(temp - 48);
else if( temp >= 65 ) // 英文字轉十進位數字
arr[i] = temp - 55;
}
for( i = 0; i < len - 1; i++ )
{
if( arr[i] <= 0 )
printf("0000");
else if( arr[i] <= 1)
printf("000");
else if( arr[i] <= 3 )
printf("00");
else if( arr[i] <= 7)
printf("0");
bin(arr[i]);
}
printf("\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment