Solved

# C++ Read Two Numbers in Base, Compute sum, print out

Posted on 2003-02-19

My starting code is in binary. I just wanted to make it octal and add the numbers.

*/

#include <stdio.h>

short decimal2binary(unsigned long decimal_value, char

binary_value[32])

{

short index,significant_digits=0;

unsigned long temp_value;

for(index=31;index>=0;index--)

{

// temp_value=decimal_value/pow(2,index)

temp_value=decimal_value/(1<<index);

if(temp_value>0)

{

binary_value[index]=(char)('0'+temp_value);

// decimal_value=decimal_value%pow(2,index)

decimal_value=decimal_value%(1<<index);

if(!significant_digits)

significant_digits=index;

}

else

{

binary_value[index]='0';

}

}

return significant_digits;

}

short decimal2hex(unsigned long decimal_value, char hex_value[8])

{

short index,significant_digits=0;

unsigned long temp_value;

for(index=7;index>=0;index--)

{

// temp_value=decimal_value/pow(16,index)

temp_value=decimal_value/(1<<(index<<2));

if(temp_value>9)

{

hex_value[index]=(char)('A'-10+temp_value);

// decimal_value=decimal_value%pow(16,index)

decimal_value=decimal_value%(1<<(index<<2));

if(!significant_digits)

significant_digits=index;

}

else if(temp_value>0)

{

hex_value[index]=(char)('0'+temp_value);

// decimal_value=decimal_value%pow(16,index)

decimal_value=decimal_value%(1<<(index<<2));

if(!significant_digits)

significant_digits=index;

}

else

{

hex_value[index]='0';

}

}

return significant_digits;

}

void main()

{

short significant_digits,index;

char hex_value[8];

char binary_value[32];

/*

* Hex conversion

*/

significant_digits=decimal2hex(0x0123FEDC,hex_value);

printf("0x0123FEDC = 0x");

/*

* With leading zeros ...

* for(index=8;index>=0;index--)

*/

for(index=significant_digits;index>=0;index--)

printf("%c",hex_value[index]);

/*

* Binary conversion next

*/

significant_digits=decimal2binary(0x0123FEDC,binary_value);

printf(" = 0b");

/*

* Leading zeros...

* for(index=31;index>=0;index--)

*/

for(index=significant_digits;index>=0;index--)

printf("%c",binary_value[index]);

printf("\n");

}