hey im trying to create a program to convert dec to hex , but this only lets me print either integers or chars , but not both , how do i fix that ?

int convertHex(int num)
{
	quotient=(num / 16);
	remainder=(num % 16);

		if (remainder <= 9 && quotient >= 1)
		{
			b[j++]=remainder;
			count++;
			convertHex(quotient);
		}
		
		else if(remainder > 9 && quotient >= 1)
		{
			b[j++]=((remainder-10)+'A');
			count++;
			convertHex(quotient);
		}
		else if(quotient <= 0)
		{	
			(remainder <= 9 ) ? (b[j++]= remainder) : (b[j++]=((remainder-10)+'A'));
			count++;
		
			//reverse(b,count);
			for( j = 0 ; j < count ; j++)
			printf("%d",b[j]);
			
		printf("\n");
		
		b[bits];
		count = 0;
		for (j = 0; j < count; ++j)
		{
			b[j] = 0;
		}
		return b[0];
	}
}

ive also written another function but it displays the number in reverse ?

int convertHex(int num)
{
	quotient=(num / 16);
	remainder=(num % 16);

		if (remainder <= 9 && quotient >= 1)
		{
			printf("%d",remainder);
			convertHex(quotient);
		}
		
		else if(remainder > 9 && quotient >= 1)
		{
			printf("%c",((remainder-10)+'A'));
			convertHex(quotient);
		}
		else if(quotient <= 0)
		{	
			(remainder <= 9 ) ? printf("%d",remainder): printf("%c",((remainder-10)+'A'));
			printf("\n");
			return 0;
		}
}

can anyone fix either one ?..please..i need to submit it before monday!
p.s - were not allowed to use %x :(

Recommended Answers

All 9 Replies

I am assuming you are working with positive integers.
Tell me how can quotient = num/16 ever be negative? You are testing for it in both functions.

Why don't you put a few test printf's in to see what's going on.

b[j++]=((remainder-10)+'A'); This doesn't behave the way you want it to behave. I'm assuming that b[] is an array of integers. The above expression will only store ascii values of A,B,C,D,E,F.

I suppose modifying your printf statement within the for loop will solve your problem.

for( j = count-1 ; j >=0 ; j--)
if(b[j]>=65)
  printf("%c",b[j]); //this prints the character which corresponds to the ascii value in b[j]
else
  printf("%d",b[j]); //this will work since b[] will never have a number greater than 9. If it does, then it'll also be greater than 64

As for the reversing the numbers, you can just start your for loop from 'count' and decrease to 0. That can't be done in the second function, since you aren't storing the results in any array, but displaying them as soon as you compute them.

Lemme know if that works. Cheers :)

Or even use a debugger, and put the variables in the watch window, so you can see what happens as you single step the code.
So long as you can imagine what should happen next, that's all you need.
So that when something you didn't expect happens, you've found a bug.

b[j++]=((remainder-10)+'A'); This doesn't behave the way you want it to behave. I'm assuming that b[] is an array of integers. The above expression will only store ascii values of A,B,C,D,E,F.

I suppose modifying your printf statement within the for loop will solve your problem.

for( j = count-1 ; j >=0 ; j--)
if(b[j]>=65)
  printf("%c",b[j]); //this prints the character which corresponds to the ascii value in b[j]
else
  printf("%d",b[j]); //this will work since b[] will never have a number greater than 9. If it does, then it'll also be greater than 64

As for the reversing the numbers, you can just start your for loop from 'count' and decrease to 0. That can't be done in the second function, since you aren't storing the results in any array, but displaying them as soon as you compute them.

Lemme know if that works. Cheers :)

It worked!! , thank you soo much!! your a genius! :D :D :D

REVERSED ORDER

char sh[100]="";
char sh1[100];
int convertHex(int num)
{
    quotient=(num / 16);
    remainder=(num % 16);

        if (remainder <= 9 && quotient >= 1)
        {
            printf("%d",remainder);
            convertHex(quotient);
                       sprintf(sh1,"%d",remainder);
                        strcat(sh,sh1);

        }

        else if(remainder > 9 && quotient >= 1)
        {
            printf("%c",((remainder-10)+'A'));
            convertHex(quotient);
                         sprintf(sh1,"%c",(remainder-10)+'A'));
                        strcat(sh,sh1);
        }
        else if(quotient <= 0)
        {   
            if(remainder <= 9 ) 
                       {
                            printf("%d",remainder);
                                sprintf(sh1,"%d",remainder);
                        strcat(sh,sh1);
                           }
                       else
                         {
                         printf("%c",((remainder-10)+'A'));
                           sprintf(sh1,"%c",(remainder-10)+'A'));
                        strcat(sh,sh1);
                         }
            printf("\n");
            return 0;
        }
}

int main()
{
    convertHex(i5798);
    printf("Sh:%s",sh);

}

How about a completely different approach that avoids all the dividing and most of the comparisons and is easily extensible to longer word lengths and can be fixed up to return the string.

#include <stdlib.h>

/* Notes:

	1) Internal representation of ALL numbers is already in hex. For this reason, simplest hex print function would always use "&" and bit shifting.
	2) Characters formed by adding "0" to low order bits and correcting for A-F.
	3) Simplest loop processes low order byte first - this means value will be printed in reverse.
	4) Simple solution is to store characters in string and index in reverse. This makes routine more easily extensible to longer word sizes.
	5) Size of int is not assumed - this covers issues with 32-bit vs 64-bit, etc.*/

void pHex(int num){
	int stages=sizeof(int)*2;	//2 characters per byte.
	char *digits = (char *) malloc (stages+1);	//Allocate with room for stages characters+terminator
	digits[stages]=0;	//Set terminator right away

/*As long as num is non-zero, loop to accumulate digits. This paradigm will suppress
 leading zeros by default. Leading zeros can be added by obvious modification (i.e.
 use for loop with stages as loop variable.)*/

	while (num) {	//As long as value is not zero
		digits[--stages]=(num & 0xf)+'0';	//pre-decrement and make provisional digit (0-9)
		if (digits[stages]>'9'){	//Correct for digits a-f
			digits[stages] += ('a'-'9'-1);	//If >9, use a-f (for upper case use 'A')
		}
		num>>=4;	//Position next digit with bit shift
	}

/*Now print the result. digits+stages will only print the digits in the string. If
 you add in leading zeros, then use just digits. You can also modify routine to
 return as string using a strdup and defining the routine as char ** instead of void.*/

	printf("0x%s\n",digits+stages);		//Print digits
	free(digits);	//remember to free the buffer!
}

Ok, It's my turn of trying a different way of solving the problem: After half a Year C in school, I came accross this solution. If you wanna see the excecuted file, I've uploadet the Picture to :The Picture and Code of the Programm Dez-hex wandler

/*
Titel: Dezimal-Hex-Wandler
Datei dezhex.cpp
Autor: Jonathan Ernst
Datum: 19.09.2011

Funktion:
Eine über die Tastatur eingelesene natürliche Zahl ist einer Funktion zu übergeben,
die eine Umwandlung in den Hex-Code vornimmt.
*/
#include <cstdlib>
#include <iostream>
#include <conio.h>
#include <stdio.h>
#include <string.h>
//-------------------------------------------------------------------------------------------
char result[100];      // Bestimmt eine Zeichenkette result mit 100 Speicherplätzen

void dechex (int deci) // Funktion dechex
{
//bestimmen der Variablen:

int zahl = 1;          //definition Variable zahl
int rest = 0;          //definition Variable rest
int counter = 0;       //Definition Variable counter, zählet +
int counterminus = 1;  //definition Variable counterminus, zählt minus
int x = 0;             //definition Variable x
int decim = deci;      //definition variable decim = deci, übernimmt den Wert der dezimalzahl.

strcpy(result," ");    //setzt den String result = 0

while (zahl !=0)        //Erste while schlaufe zur berechnung der Anzahl stellen welche die Hexzahl haben wird.
{
zahl = decim/16;        //Berechnet: beispiel: dezimal Zahl 77 : 16 = 4, 4 wird in Variable Zahl gespeichert.
rest = decim - (zahl*16);//berechnet den Restwert. : 77-(4*16)=77-64=13
decim = zahl;            //die Zahl 13 währe die höchstwertige ziffer der hex-zahl
counter++;               //zählt die anzahl Zyklen
}
counterminus = counter;   // counterminus wird mit counter gleichgesetzt, counterminus wird benützt um die Reihenfolge der hex-Ziffern zu bestimmen.
zahl = 1;                 // setzt zahl wieder gleich 1

while (zahl !=0)          //zweite Schleife, Jetzt werden die erhaltenen Werte in einem String (result) gespeichert.
{
zahl = deci/16;             //Berechnet: beispiel: dezimal Zahl 77 : 16 = 4, 4 wird in Variable Zahl gespeichert.
rest = deci - (zahl*16);    //berechnet den Restwert. : 77-(4*16)=77-64=13
deci = zahl;                //die Zahl 13 währe die höchstwertige ziffer der hex-zahl

if (rest == 0)                //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='0'; } // beim ersten Durchgang hat Counterminus den höchsten wert, somit wird die Ziffer auf die Letzte stelle geschrieben.

if (rest == 1)                //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='1'; } // beim zweiten durchgang wird die zweitletzte stelle beschrieben.

if (rest == 2)                //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='2'; }  //schreibt den Wert 2 in string Result an angegebener (counter minus) stelle

if (rest == 3)                //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='3'; } //schreibt den Wert 3 in string Result an angegebener (counter minus) stelle

if (rest == 4)                //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='4'; } //schreibt den Wert 4 in string Result an angegebener (counter minus) stelle

if (rest == 5)               //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='5'; }//schreibt den Wert 5 in string Result an angegebener (counter minus) stelle

if (rest == 6)               //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='6'; }//schreibt den Wert 6 in string Result an angegebener (counter minus) stelle

if (rest == 7)               //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='7'; }//schreibt den Wert 7 in string Result an angegebener (counter minus) stelle

if (rest == 8)               //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='8'; } //schreibt den Wert 8 in string Result an angegebener (counter minus) stelle

if (rest == 9)               //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='9'; }//schreibt den Wert 9 in string Result an angegebener (counter minus) stelle

if (rest == 10)              //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='A'; } //schreibt den Wert A in string Result an angegebener (counter minus) stelle

if (rest == 11)             //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{result[counterminus]='B'; }//schreibt den Wert B in string Result an angegebener (counter minus) stelle

if (rest == 12)            //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{result[counterminus]='C'; }//schreibt den Wert C in string Result an angegebener (counter minus) stelle

if (rest == 13)             //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{ result[counterminus]='D'; } //schreibt den Wert D in string Result an angegebener (counter minus) stelle

if (rest == 14)             //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{result[counterminus]='E'; }//schreibt den Wert E in string Result an angegebener (counter minus) stelle

if (rest == 15)             //  wenn der rest = null wäre würde diese Ziffer angezeigt.
{result[counterminus]='F'; } //schreibt den Wert F in string Result an angegebener (counter minus) stelle

counterminus--;             // zählt runter.
}
printf("%s",result);        //schreibt das Resultat!! in hex, string result

}

int main(void)               //Aufruf

{
int dec = 0; //Deklaration Variable dec
char exit = 'a';

while ( exit != 'n')
{ 
printf("\n Bitte geben Sie eine Dezimal Zahl ein: "); //Ausgabe Text
scanf("%i",&amp;dec); // Texteingabe

printf("\n %i schreibt man in Hexadezimalsystem so: ", dec); //Ausgabe Text
dechex(dec); //Funktionsaufruf hexdec

printf("\nM\224chten sie eine andere Zahl umwandeln? j/n ");
fflush(stdin);
exit = getchar();
fflush(stdin);
} //warte
return 0; //ende
}

SO how do you like my code?.

Ok, It's my turn of trying a different way of solving the problem:
. . .
SO how do you like my code?.

It's bad...
1) Two years too late
2) No formatting making the code hard to follow
3) Using fflush(stdin); -- not defined for input streams
4) Using sequential IFs instead of SWITCH.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.