So this code changes hexadecimal to binary digits. A specific hexadecimal number I should add. It is not built for all.
I mean, this does exactly what I want... But I was just wondering if there is a simpler way to do this with a loop? I tried a for() and a while() loop but just failed at it. They turned into infinity loops and I couldn't break them hahaha so I went with plan B above.
Just wondering for future reference.
#include <stdio.h> #include <conio.h> #include <math.h> int main() { int decimal, y, z, x, w, dec, dec1, dec2, a, b, c, d, e, v, u, t, s, r, q, p, o, dec3, dec4, dec5, dec6, dec7, dec8, dec9, dec10; printf("The Hexadecimal number is: 0xCCCDB\n"); a = 12 * pow(16.0, 4); //C \ b = 12 * pow(16.0, 3); //C - Hex value of 'C' is 12, so we take 12 times 16^(position of C in the hex code) c = 12 * pow(16.0, 2); //C / d = 13 * pow(16.0, 1); //D - Hex value of 'D' is 13, so we take 13 times 16^(position of D in hex code) e = 11 * pow(16.0, 0); //B - Hex value of 'B' is 11, so we take 11 times 16^(position of B in hex code) decimal = a + b + c + d + e; printf("Decimal = %d\n", decimal); //Calculates 4 bit binary digit for the hexadecimal digit 'B' z = decimal % 2; dec = decimal / 2; y = dec % 2; dec1 = dec / 2; x = dec1 % 2; dec2 = dec1 / 2; w = dec2 % 2; dec3 = dec2 / 2; //Calculates 4 bit binary digit for the hexadecimal digit 'D' v = dec3 % 2; dec4 = dec3 / 2; u = dec4 % 2; dec5 = dec4 / 2; t = dec5 % 2; dec6 = dec5 / 2; s = dec6 % 2; dec7 = dec6 / 2; //Calculates 4 bit binary digit for the hexadecimal digit 'C' r = dec7 % 2; dec8 = dec7 / 2; q = dec8 % 2; dec9 = dec8 / 2; p = dec9 % 2; dec10 = dec9 / 2; o = dec10 % 2; printf("%d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d %d%d%d%d", o, p, q, r, o, p, q, r, o, p, q, r, s, t, u, v, w, x, y, z); //Order variables backwards to print correct order of binary number. getch(); return 0; }
I mean, this does exactly what I want... But I was just wondering if there is a simpler way to do this with a loop? I tried a for() and a while() loop but just failed at it. They turned into infinity loops and I couldn't break them hahaha so I went with plan B above.
Just wondering for future reference.