Hi! I have a hexadecimal word in the form of a string, and i need to convert it into binary.
For eg : AA FF (there is a space in between the two parts). How do i convert this into binary ?
Thanks in advance :)
Hi! I have a hexadecimal word in the form of a string, and i need to convert it into binary.
For eg : AA FF (there is a space in between the two parts). How do i convert this into binary ?
Thanks in advance :)
By "binary" I assume you mean a string in which each character is a one or a zero.
Read in a char. Output four chars depending on what that input is, according to this table: http://www.learn44.com/wp-content/uploads/2011/08/Binary-to-Decimal-and-Hexadecimal-Conversion-Memorization-Chart.jpg
So AA would be 10101010
But how do i handle spaces in between ?
If you want to retain the spaces in the output, if the input char is a space, output a space.
If you don't want to retain the spaces in the output, if the input char is a space, output nothing.
I think you really could have worked this out for yourself.
i'm sorry , but i'm new to programming.
whenever i encounter a space ,it stops converting. For example something like " BB 13" - In this space the part before the space alone is converted. the code is below .
Thanks :)
#include<stdio.h>
#include<conio.h>
#define MAX 1000
int main(){
char binaryNumber[MAX], hexaDecimal[MAX];
long int i = 0;
printf("Enter any hexadecimal number: ");
scanf("%s", hexaDecimal);
printf("\nEquivalent binary value: ");
while (hexaDecimal[i]){
switch (hexaDecimal[i]){
case '0': printf("0000"); break;
case '1': printf("0001"); break;
case '2': printf("0010"); break;
case '3': printf("0011"); break;
case '4': printf("0100"); break;
case '5': printf("0101"); break;
case '6': printf("0110"); break;
case '7': printf("0111"); break;
case '8': printf("1000"); break;
case '9': printf("1001"); break;
case 'A': printf("1010"); break;
case 'B': printf("1011"); break;
case 'C': printf("1100"); break;
case 'D': printf("1101"); break;
case 'E': printf("1110"); break;
case 'F': printf("1111"); break;
case 'a': printf("1010"); break;
case 'b': printf("1011"); break;
case 'c': printf("1100"); break;
case 'd': printf("1101"); break;
case 'e': printf("1110"); break;
case 'f': printf("1111"); break;
case ' ': printf(" "); break;
default: printf("\nInvalid hexadecimal digit %c ", hexaDecimal[i]);
}
i++;
}
getch();
return 0;
}
scanf
with the %s
parameter stops at spaces.
Either scanf
again, over and over, or use fgets
or getline
to just read in the entire thing. https://stackoverflow.com/questions/1247989/how-do-you-allow-spaces-to-be-entered-using-scanf
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.