Michael
Michael

Reputation: 25

Incorrect decimal to hexadecimal conversion - C

I wrote this function from a pseudocode I found, which should convert decimal input into hexadecimal number. Well it does that, but in incorrect order, like for example, for decimal number 195 I get 3C, insted of C3.

int temp=0;
int i=0;
while(decimal!=0)
{
    temp = decimal % 16;
    if( temp < 10)
        temp =temp + 48;
    else
        temp = temp + 55;
    array[i++]= temp;
    decimal = decimal / 16;
}

Upvotes: 0

Views: 154

Answers (1)

Rob Johnson
Rob Johnson

Reputation: 46

save yourself some time like this

#include <stdio.h>
// ...
sprintf(hexStr,"%X",decimal);   // or, "%#X" if you want prefix

unless, this is homework for a programming class. in which case you should really just work it out on whiteboard or paper, i'm sure you'll see your mistake.

Upvotes: 2

Related Questions