Click here to Skip to main content
15,887,485 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
  int n,r;
  char k;
  char binary[100]=" ";

    printf("ENTER THE NUMBER IN HEXADECIMAL\n");
    scanf("%d",&n);
    while(n!=0)
    {
        r=n%10;
        k=(char)r;
        switch(k)
        {
            case '0':
                strcat(binary,"0000");
                break;
            case '1':
                strcat(binary,"0001");
                break;
            case '2':
                strcat(binary,"0010");
                break;
            case '3':
                strcat(binary,"0011");
                break;
            case '4':
                strcat(binary,"0100");
                break;
            case '5':
                strcat(binary,"0101");
                break;
            case '6':
                strcat(binary,"0110");
                break;
            case '7':
                strcat(binary,"0111");
                break;
            case '8':
                strcat(binary,"1000");
                break;
            case '9':
                strcat(binary,"1001");
                break;
            case 'a':
                case 'A':
                    strcat(binary,"1010");
                    break;
            case 'b':
                case 'B':
                    strcat(binary,"1011");
                    break;
            case 'c':
                case 'C':
                    strcat(binary,"1100");
                    break;
            case 'd':
                case 'D':
                    strcat(binary,"1101");
                    break;
            case 'e':
                case 'E':
                    strcat(binary,"1110");
                    break;
            case 'f':
                case 'F':
                    strcat(binary,"1111");
                    break;
        }
        n=n/10;
    }
    strrev(binary);
    printf("%s",binary);
    return 0;
}


What I have tried:

i am trying to print the binary code of the hexadecimal number.
Posted
Updated 1-Jul-20 23:37pm
v2

Lots of reasons!

1) Because you are extracting digits in the wrong order.
If I enter "1a3" then your loop will first extract the "3", then the "a", then the "1".
You need to work from the most significant digit first not the least, or reverse the output before you print it.
Hint: If you work from the end of binary instead of the front it might work better.

2) Because the "%" operator returns an integer, not a character.
3 in an integer is not the same as '3' the character value, and when you cast an integer to a char value, it doesn't change it: it leave it as the value 3 in a char variable. That isn't the same as '3' which has a value of 0x33: ASCII - Wikipedia[^]
3 the value in a char is what is called a "control code" called "ETX", and it=s used to "Frame" data.
Hint: Remove the quotes from your cases and try again:
C++
            case 0:
                strcat(binary,"0000");
                break;
            case 1:
                strcat(binary,"0001");
                break;
...
You will need to do something about 'a' to 'f', but I'll leave that to you.
Suggestion: Always add a default to a switch so do something sensible when you get a value you haven't allowed for: print it with an error message, for r example.

3) Because x % 10 doesn't give you a hexadecimal digit: it gives you a decimal digit. Likewise, x / 10 doesn't discard a hex digit but a decimal one.
Hint: try using 16 instead of 10, or extract a hex digit by ANDing it 0x0f.

4) Because scanf("%d", ...) doesn't read a hexadecimal number: scanf format string - Wikipedia[^]
Hint: There is no format code for "read a hex number": either read a decimal number and convert that to binary, or read a string and validate it before converting to a numeric value.

To be honest, you should have spotted most of these pretty quickly for yourself: if you had used the debugger to see what was happening, you would have had an easier time.
I would strongly suggest that you learn how to use the debugger on your system - it can let you look at and control your code while it is running, including examining and changing the value of variables. It's the most powerful tool you have, and you will probably spend more time there testing and fixing your code than you will writing it!

If you don't know how to use a debugger, then Google will help - search for the name of your IDE and "Debugger" and you will find loads of information!
 
Share this answer
 
I prefer to "peel off" the bits. Here is a function that does some bit shifting to get the binary string for one byte and it inserts a space between the two nibbles.
C++
typedef unsigned char UCHAR;

void GenerateBinaryString( UCHAR byt, char * buffer )
{
   int n = 0;
   char * appendstr = nullptr;
   UCHAR mask = 0;

   * buffer = 0;
   for( n = 0; n < 8; ++n )
   {
       mask = 1 << ( 7 - n );
       appendstr = ( byt & mask ) ? "1" : "0";
       strcat( buffer, appendstr );
       if( n == 3 )
           strcat( buffer, " " );  // insert a space between nibbles
   }
}
Then you call it for each byte of data you have. With a loop you could handle data of any size.

Here is a function to test this. It displays the decimal, hexadecimal, and binary values of numbers between 0 and 255.
C++
void TestBinaryStrings()
{
    char buffer[ 16 ] = { 0 };
    for( int n = 0; n < 256; ++n )
    {
        GenerateBinaryString( (UCHAR) n, buffer );
        printf( "%3d = 0x%02X = %s\n", n, n, buffer );
    }
}
In my tests results are as expected.
 
Share this answer
 
v2
You can fulfill the requirements using just strings (that is array of characters). Try
C
#include <stdio.h>
#include <string.h>

int main()
{
  const size_t HEX_DIGITS = 8;
  const size_t BIN_DIGITS = HEX_DIGITS * 4;
  int hex_index;
  int bin_index;
  int is_hex_digit;

  char hex[HEX_DIGITS+1];
  char bin[BIN_DIGITS+1];
  printf("please enter the hexadecimal representation of the number\n");
  fgets(hex, sizeof(hex), stdin);

  for (bin[0] = '\0', hex_index = 0, bin_index = 0, is_hex_digit = 1; is_hex_digit; ++hex_index, bin_index+=4)
  {
    switch( hex[hex_index] )
    {
    case '0':
      strcat(&bin[bin_index], "0000");
      break;
    case '1':
      strcat(&bin[bin_index], "0001");
      break;
    case '2':
      strcat(&bin[bin_index], "0010");
      break;
    case '3':
      strcat(&bin[bin_index], "0011");
      break;
    case '4':
      strcat(&bin[bin_index], "0100");
      break;
    case '5':
      strcat(&bin[bin_index], "0101");
      break;
    case '6':
      strcat(&bin[bin_index], "0110");
      break;
    case '7':
      strcat(&bin[bin_index], "0111");
      break;
    case '8':
      strcat(&bin[bin_index], "1000");
      break;
    case '9':
      strcat(&bin[bin_index], "1001");
      break;
    case 'A':
    case 'a':
      strcat(&bin[bin_index], "1010");
      break;
    case 'B':
    case 'b':
      strcat(&bin[bin_index], "1011");
      break;
    case 'C':
    case 'c':
      strcat(&bin[bin_index], "1100");
      break;
    case 'D':
    case 'd':
      strcat(&bin[bin_index], "1101");
      break;
    case 'E':
    case 'e':
      strcat(&bin[bin_index], "1110");
      break;
    case 'F':
    case 'f':
      strcat(&bin[bin_index], "1111");
      break;
    default:
      is_hex_digit = 0;
      break;
    }
  }
  printf("binary representation is  %s\n", bin);
  return 0;
}
 
Share this answer
 
v2
C++
r=n%10;

Hexadecimal means base 16, not 10.
C++
k=(char)r;

This says that k is a char with ascii code r, it don't do any conversion to the char you expect, because you didn't asked for a conversion.
Try with
C++
switch(r)
{
    case 0:
        strcat(binary,"0000");
        break;
    case 1:
        strcat(binary,"0001");
        break;

Quote:
Why thefollowing code don't print the binary number of respective hexadecimal number?

Your code do not behave the way you expect, or you don't understand why !

There is an almost universal solution: Run your code on debugger step by step, inspect variables.
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't know what your code is supposed to do, it don't find bugs, it just help you to by showing you what is going on. When the code don't do what is expected, you are close to a bug.
To see what your code is doing: Just set a breakpoint and see your code performing, the debugger allow you to execute lines 1 by 1 and to inspect variables as it execute.

Debugger - Wikipedia, the free encyclopedia[^]

Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
Basic Debugging with Visual Studio 2010 - YouTube[^]

1.11 — Debugging your program (stepping and breakpoints) | Learn C++[^]

The debugger is here to only show you what your code is doing and your task is to compare with what it should do.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900