برنامج صغير كل وظيفته انه يحول من الاعداد العشريه للسداسية عشر او العكس
لو عدلت فيه شوية تعديلات بسيطه هتقدر انك تستخدمه في تحويل اي نوع من انواع الارقام سداسية عشر ثنائيه رباعيه سباعيه اي حاجه للعشري او العكس
الفكره بسيطه جدا , تطبيقها عليك
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <unistd.h>
#define POWER ((len - through) - 1)
/* Static character pointer to the program name */
static char *program_name;
/* Character of hexdecimal system */
enum hex{a=10,b,c,d,e,f};
/* Verbose */
int v = 0;
void usage(const char *name)
{
fprintf(stderr , "%s [option] number\n",name);
fprintf(stderr , "options:\n"
"\t -t to hex\n"
"\t -d to dec\n"
"\t -v verbose\n");
exit(0);
}
void to_hex(const char *number)
{
long digit = 0;
long through = 1;
int index = 0;
char hexed[20];
digit = atol(number);
if(digit == 0)
{
printf("0H\n");
return ;
}
while(through <= digit)
through *= 16;
if(through > digit)
through /= 16;
while(through != 0)
{
int rem = digit / through;
if(v)
printf("Deviding %ld / %ld\n",digit,through);
switch(rem)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
sprintf(&hexed[index++],"%d",rem);
break;
case 10:
hexed[index++] = 'a';
break;
case 11:
hexed[index++] = 'b';
break;
case 12:
hexed[index++]= 'c';
break;
case 13:
hexed[index++] = 'd';
break;
case 14:
hexed[index++] = 'e';
break;
case 15:
hexed[index++] = 'f';
break;
}
digit -= rem * through;
through /= 16;
}
hexed[index] = '\0';
printf("%sH\n",hexed);
}
void from_hex(const char *number)
{
int len = strlen(number);
int through = 0;
long digit = 0;
if(len <= 0)
usage(program_name);
for(through = len - 1 ; through >= 0 ; through--)
{
if(number[through] == 'h' || number[through] == 'H')
--len;
else
break;
}
for(through = len - 1 ; through >= 0 ; through--)
{
if(v)
printf("Multiplaying %d with 16 ^ %d\n",number[through] - '0' , len - through);
switch(number[through])
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
digit += (number[through] - '0' ) * (pow(16 , POWER));
break;
case 'A':
case 'a':
digit += a * pow(16 , POWER);
break;
case 'B':
case 'b':
digit += b * pow(16 , POWER);
break;
case 'C':
case 'c':
digit += b * pow(16 , POWER);
break;
case 'D':
case 'd':
digit += d * pow(16 , POWER);
break;
case 'E':
case 'e':
digit += e * pow(16 , POWER);
break;
case 'F':
case 'f':
digit += f * pow(16 , POWER);
break;
case 'H':
case 'h':
continue;
break;
default:
usage(program_name);
break;
}
}
printf("%ld\n",digit);
}
int main(int argc , char **argv)
{
char c;
const char *optstring = "t:d:vh";
program_name = argv[0];
if(!argv[1])
{
usage(program_name);
}
while((c = getopt(argc,argv,optstring)) != -1)
{
switch(c)
{
case 't':
to_hex(optarg);
break;
case 'd':
from_hex(optarg);
break;
case 'v':
v = 1;
break;
case 'h':
usage(program_name);
break;
default:
usage(program_name);
break;
}
}
return 0;
}