Teaching my brother decimal to hexadecimal, binary to decimal
#include <stdio.h>
#include <string.h>
void IntToHex(unsigned int n, char hexDigitOutput[])
{
char hexTable[] = "0123456789ABCDEF";
int rem;
int index;
memset(hexDigitOutput, '0', 8);
hexDigitOutput[8] = 0;
index = 7;
while (n > 0)
{
rem = n % 16;
n = n / 16;
hexDigitOutput[index] = hexTable[rem];
--index;
}
}
int BinaryToDec(char *bin)
{
int len;
int output;
int n2;
len = strlen(bin);
output = 0;
n2 = 1;
while(--len >= 0)
{
output += n2 * (bin[len] - '0');
n2 <<= 1;
}
return output;
}
int main (int argc, char *argv[])
{
int i;
char output[9];
char binary[33];
printf ("Hello world!\n");
for(i = 0; i <= 32; ++i)
{
IntToHex(i, output);
printf("\nI: %d Hex: %s", i, output);
}
strcpy(binary, "1101");
printf("\nBinary: %s Decimal: %d", binary, BinaryToDec(binary));
return 0;
}
Hello world!
I: 0 Hex: 00000000
I: 1 Hex: 00000001
I: 2 Hex: 00000002
I: 3 Hex: 00000003
I: 4 Hex: 00000004
I: 5 Hex: 00000005
I: 6 Hex: 00000006
I: 7 Hex: 00000007
I: 8 Hex: 00000008
I: 9 Hex: 00000009
I: 10 Hex: 0000000A
I: 11 Hex: 0000000B
I: 12 Hex: 0000000C
I: 13 Hex: 0000000D
I: 14 Hex: 0000000E
I: 15 Hex: 0000000F
I: 16 Hex: 00000010
I: 17 Hex: 00000011
I: 18 Hex: 00000012
I: 19 Hex: 00000013
I: 20 Hex: 00000014
I: 21 Hex: 00000015
I: 22 Hex: 00000016
I: 23 Hex: 00000017
I: 24 Hex: 00000018
I: 25 Hex: 00000019
I: 26 Hex: 0000001A
I: 27 Hex: 0000001B
I: 28 Hex: 0000001C
I: 29 Hex: 0000001D
I: 30 Hex: 0000001E
I: 31 Hex: 0000001F
I: 32 Hex: 00000020
Binary: 1101 Decimal: 13
No comments:
Post a Comment