Home > front end >  My decimal to hex conversion function only woks with positive nums
My decimal to hex conversion function only woks with positive nums

Time:05-06

I'm having problems converting negative numbers, from decimal base to hexadecimal base, with the following function:

#include <stdio.h>
 
int main()
{
    int quotient, remainder;
    int i, j = 0;
    char hexadecimalnum[100];
 
    quotient = -50;
 
    while (quotient != 0)
    {
        remainder = quotient % 16;
        if (remainder < 10)
            hexadecimalnum[j  ] = 48   remainder;
        else
            hexadecimalnum[j  ] = 55   remainder;
        quotient = quotient / 16;
    }

    strrev(hexadecimalnum);

    printf("%s", hexadecimalnum);
    return 0;
}

For quotient = -50; the correct output should be:

ffffffce

But this function's output is:

.

With positive numbers the output is always correct but with negative numbers not.

I'm having a hard time understanding to why it doesn't work with negative numbers.

CodePudding user response:

Some fixes:

  • unsigned int quotient - you need to convert -50 to a large hex number in two's complement or you'll get the wrong number of iterations (2) in the loop, instead of 8 as required.
  • Removal of "magic numbers": '0' remainder and 'A' remainder - 10.
  • Zero initialize hexadecimalnum becaues it needs to be null terminated before printing a string from there. Better yet, add the null termination explicitly.
  • Use for loops when possible.
  • Might as well store the characters from the back to front and save the extra call of reversing the string.

Result:

#include <stdio.h>

// 4 bytes*2 = 8 nibbles
#define HEX_STRLEN (sizeof(int)*2) 
 
int main()
{
    unsigned int remainder;
    int i = 0;
    char hex[100];
 
    for(unsigned int q = -50; q!=0; q/=16)
    {
      remainder = q % 16;
      if (remainder < 10)
        hex[HEX_STRLEN-i-1] = '0'   remainder;
      else
        hex[HEX_STRLEN-i-1] = 'A'   remainder - 10;
      i  ;
    }
    hex[HEX_STRLEN] = '\0'; // explict null termination
    printf("%s\n", hex);
}

(There's lots of improvements than can be made still, this is just to be considered as the first draft.)

CodePudding user response:

You can use printf's format specifier "x", then you can print any number in their respective hexadecimal representation.

#include <stdio.h>

void num_to_hex(int a, char *ptr) { snprintf(ptr, 9, "x", a); }

int main() {
    char hex[10] = {};
    num_to_hex(-50, hex);
    printf("%s\n", hex);
    return 0;
}

Output:

ffffffce
  •  Tags:  
  • c
  • Related