Alright guys, I've been trying to think how to do this and I keep confusing myself.

It's part of a project using piping in UNIX but first I need to get this small program running properly. I want to pass the final result (Hex value) to another program that will convert that result to binary.

This is my current code, which runs fine, although I was thinking of storing the value where is says printf("A"); ,for example, into an array.

Although, I need to pass the array to another program which is looking for an int value. I think the best way is to concatenate this array into a single variable (If possible!) and pass this instead.

int n,r[10],i=0,number,j=0;
printf("Enter a decimal number: ");
scanf("%d",&number);



while(number>0)
{
r[i] = number % 16;
number=number / 16;
i++;
j++;
}
printf("The hexadecimal equivalent is: ");
for(i=j-1;i>=0;i--)
{
if(r[i]==10)
printf("A");
else if(r[i]==11)
printf("B");
else if(r[i]==12)
printf("C");
else if(r[i]==13)
printf("D");
else if(r[i]==14)
printf("E");
else if(r[i]==15)
printf("F");
else
printf("%d",r[i]);
}


printf("\n");

}

What do you guys think?

NOTE: I'm converting this way as we're not supposed to use any short cuts during the conversion, such as methods in libraries or system calls etc.

Thanks,

Dec28

I don't understand.
You need to convert an array of hex values that you output into an integer? Even though you input that integer in the first place? You question is quite confusing.

Maybe some details and definitions would help us make sense of your question.

If I understand, you are going to use this with pipes later so would leave the output of this program as ASCII. That way it is easy to debug. As for the "passing of a single variable", you are working with pipes and you would not be passing variables but using the standard output of one program as the input to the other program. That is why I say leave it ASCII and change the other program to read strings. Again if the other program take a hex number and converts that to binary, how are you going to test it by itself if the input is not something you can type at the command line? I see it like this:

$ ./dec2hex 11
0xB
$ ./hex2bin 0xB
1011
$ ./dec2hex 11 | ./hex2bin
1011
$

Now after doing that I also realized that you would need to check if there are no command args then the input would be standard input. Doing this would allow you to test each one I indypendently and then piped.

if ( argc == 1 ) {
/* Read input from stdin */
scanf("%d",&number);
} 
else {
/* Read from command line */
number = atoi(argv[1]);
}

Ofcouse add some error checking.

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.