Friday, August 12, 2022

[FIXED] How come my binary number isn't properly converting to hexadecimal?

Issue

I am trying to convert a binary number to a hexadecimal number by converting the binary number to decimal first, then to hexadecimal.

When I run the part that converts decimal to hexadecimal alone, it works fine, but whenever I try to run both, it doesn't work?


for (returnBinary = length - 1; returnBinary > -1; returnBinary--) {

     if (input[returnBinary] == '1') {
        binDec = binDec + power(2, length - returnBinary - 1);
     }

}

// decimal to hex

while (binDec != 0) {

      remainder = binDec % 16;

       if (remainder < 10) {

         hexResult[returnBinary++] = 48 + remainder;

        } else {

         hexResult[returnBinary++] = 55 + remainder;

        }

        binDec = binDec / 16;

}

// print in reverse

printf("Your hexadecimal value is: 0x");

for (returnHex2 = returnHex; returnHex2 >= 0; returnHex2--) {
        printf("%c", hexResult[returnHex2 - 1]);
}

Each part works fine separately, but when put together it doesn't work.

EG: Converting the decimal number 60 to hex works fine, but when converting the binary equivalent of 60 (111100), it gives me a result of 0xC, when it should be 0x3C.


Solution

Tracing it through, I see that:

hex[-1] = 'C'
hex[0] = '3'

I suspect that you meant

hexResult[returnHex++] = 48 + remainder

instead of

hexResult[returnBinary++] = 48 + remainder

assuming that returnHex is initialized to zero.



Answered By - Alcamtar
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.