# hext to binary using apstring

• 10-09-2003
xxratcatxx
hext to binary using apstring
I have an assignment that I don't quite understand how to code because my teacher is a crackhead and tells us to learn from coding he's done 20 years ago.
I need to, given a hex string, write a function that returns its binary equivalent. We've only been through the basics of programming ie. apstrings, int stuff etc., so please keep it simple guys. I can't use the getline and .length commands.
He gave us these clues, which don't help me at all.

Code:

apstring hex_binary
{
}

use concatenating binary characters
hex_binary

This is what I have so far
void numbers()
{        ofstream file1;
file1.open("a:numbers.dat");
if (!file1)
{cerr <<"\n file not open";
exit(1);
}

{          long first, second, third, largest, smallest;
cout<<"Key in first character.\n";
cin >>first;
cout<<"Key in second character.\n";
cin >>second;
cout<<"Key in third character.\n";
cin >>third;

Please keep it REALLY simple because I've only programmed in C for about a month. I can only use apstrings and int stuff. I searched the boards, but everything was so complicated.
• 10-10-2003
DougDbug
First-off, I don't know exactly what an apstring is... it's non-standard.

What's file I/O got to do with the problem assignment?

There are ways to convert you input/output to and from various number-bases. But, it sounds like you're supposed to convert a hex string to a binary string, without really converting it to an integer... and you're supposed to write your own function.

So, you can use a switch-statement, or a series of if-statements to check each character in the string-array. Each character will convert to one of 16 four-bit patterns. This is why it's "easy" to convert between hex and binary... every hex digit converts to 4 binary digits. You can memorize 14 conversions (you already know zero and one), and you can convert any size numbers... Converting between decimal and binary is not so simple... you actually have to calculate.

Maybe this will get you started:
Code:

if(MyString[n] == '0')
cout << "0000";
...
if(MyString[n] == 'A')
cout << "1010";
...
if(MyString[n] == 'F')
cout << "1111";

If you haven't memorized the 14 conversions, you can use the built-in windows calculator:
Start->Programs->Accessories->Calculator->View->Scientific->Hex (or/Bin)

Finally, If your teacher is really bad, just read your book. And/or get another good beginning book. I liked Teach Yourself C++ In 21 Days, by Jesse Liberty. It may not be that he's a bad teacher. Programmming is a bit different from most subjects. I remember being totally lost for awhile in my first programming class... I didn't know what he was talking about!