1

I have a simple binary to hex and hex to binary converter, but strrev() returns "undefined reference to `strrev' collect2: ld returned 1 exit status" even though I included string.h. Is there a replacement in c for strrev() which will not require c++ or updating my linux shell?

 #include <stdio.h>
 #include <math.h>
 #include <string.h>
 void binary_hex(int n, char hex[]);
 int hex_binary(char hex[]);
 int main()
 {
     char hex[20],c;
     int n;
     printf("Instructions:\n");
     printf("Enter h to convert binary to hexadecimal:\n");
     printf("Enter b to hexadecimal number to binary:\n");
     printf("Enter a character: ");
     scanf("%c",&c);
     if (c=='h' || c=='H')
     {
         printf("Enter binary number: ");
         scanf("%d",&n);
         binary_hex(n,hex);
         printf("Hexadecimal number: %s",hex);
     }
     if (c=='b' || c=='B')
     {
         printf("Enter hexadecimal number: ");
         scanf("%s",hex);
         printf("Binary number: %d",hex_binary(hex));
     }
     return 0;
 }

 void binary_hex(int n, char hex[]) /* Function to convert binary to hexadecimal. */
 {
     int i=0,decimal=0, rem;
     while (n!=0)
     {
         decimal += (n%10)*pow(2,i);
         n/=10;
         ++i;
     }

 /* At this point, variable decimal contains binary number in decimal format. */
     i=0;
     while (decimal!=0)
     {
         rem=decimal%16;
         switch(rem)
         {
             case 10:
               hex[i]='A';
               break;
             case 11:
               hex[i]='B';
               break;
             case 12:
               hex[i]='C';
               break;
             case 13:
               hex[i]='D';
               break;
             case 14:
               hex[i]='E';
               break;
             case 15:
               hex[i]='F';
               break;
             default:
               hex[i]=rem+'0';
               break;
         }
         ++i;
         decimal/=16;
     }
     hex[i]='\0';
     strrev(hex);       /* Function to reverse string. */
 }
Kaladin
  • 19
  • 2
  • The switch in the `binary_hex` function is a bit clumsy. You could use `hex[i] = "0123456789ABCDEF"[rem];` (or you could name the array, perhaps `const char hexdigits[] = "0123456789ABCDEF";` and `hex[i] = hexdigits[rem];`), or you could use `if (rem < 10) hex[i] = rem + '0'; else hex[i] = 'A' + rem - 10;` or the ternary operator `hex[i] = (rem < 10) ? rem + '0' : rem - 10 + 'A';`. – Jonathan Leffler Oct 01 '14 at 02:37
  • I changed hex[i]='\0'; to hex[i] = (rem < 10) ? rem + '0' : rem - 10 + 'A'; and then removed the strrev(hex), but this caused a segmentation fault :) – Kaladin Oct 01 '14 at 12:52
  • You need to null-terminate the string. My comment discussed replacements for the `switch` statement inside the loop; there wasn't much need to change the rest of the function. – Jonathan Leffler Oct 01 '14 at 14:15

0 Answers0