Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Drowning - need binary to hex

Status
Not open for further replies.

walkersmafhcc

Instructor
Aug 20, 2002
3
US
HELP!

I need a small program to convert decimal to binary, and a second to convert binary to hex. Nothing fancy - a simple text(dos) screen asking for input and displaying the converted number.

I'd offer a beer in exchange for the help, but I don't think I can get it to you.. :)

Thanks to all - we appreciate it..
 
Don't normally do this sort of thing but it seems simple enough to do in between long system builds. Are you looking for 'pure' C++ or can we use C's printf?
 
Doesn't matter - I just need the cpp text to display on a whiteboard.

Thanks for your help
 
I don't know how well this formats on the message board

#include <iostream>
#include <string>
using namespace std;
void BinaryToHex (const char* binary)
{
int value = 0;
for (int i = 1; binary; i++)
{
if (binary != '0' && binary != '1') break;
value = value << 1 | (binary & 1);
}

cout << binary << &quot; = H&quot; << hex << value << endl;
}

void DecimalToBinary (const char* decimal)
{
int value = atoi (&decimal[1]);
char result[33];
char* bit = &result[sizeof (result) - 1];

*bit = '\0';
do
{
bit--;
*bit = '0' + (value & 1);
value >>= 1;
} while (bit != result && value != 0);

cout << decimal << &quot; = B&quot; << bit << endl;
}

int main ()
{
string info;
char whatToDo;

for (;;)
{
// The menu
cout << &quot;Dxxx decimal to binary conversion\n&quot;
&quot;Bxxx binary to hex conversion\n&quot;
&quot;Q Quit&quot; << endl;
cin >> info;

switch (info.at (0))
{
case 'B':
case 'b':
BinaryToHex (info.c_str ());
break;

case 'D':
case 'd':
DecimalToBinary (info.c_str ());
break;

case 'Q':
case 'q':
return 0;
break;

default:
break;
}
}
return 0;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top