# Convert a string to Binary & hexadecimal value

Hi all,

Is there a way to convert a string "ASCII" to its Decimal & hexadecimal value. For example
"Hello this is a test"

Hex:

48 65 6c 6c 6f 20 74 68 69 73 20 69 73 20 61 20 74 65 73 74

Binary:

01001000 01100101 01101100 01101100 01101111 00100000 01110100 01101000 01101001 01110011 00100000 01101001 01110011 00100000 01100001 00100000 01110100 01100101 01110011 01110100 00100000 01100011 01101111 01101110 01110110 01100101 01110010 01110100 01110011 00100000 01110100 01101111 00001101 00001010 00001101 00001010

Thanks all
###### Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Author Commented:
correction in question:

Is there a way to convert a string "ASCII" to its *Binary* & hexadecimal value.
0
Commented:
where do you want to store the result

print it, store it in a string ???
0
Commented:

#include <string>
using namespace std;

string Byte2Hex(unsigned char c)
{
const char *CnvTbl = "0123456789ABCDEF";
string S;

S = CnvTbl[c >> 8];
S += CnvTbl[c & 0x0F];
return S;
}

string Byte2Bin(unsigned char c)
{
string S;
unsigned char Msk = 0x80;

for (int i = 0; i < 8; ++i)
{
if (c & Msk)
S += '1';
else
S += '0';
Msk >>= 1;
}
return S;
}

string String2Hex(const string &S)
{
const int StrLen = S.length();
string Result;

for (int i = 0; i < StrLen; ++i)
Result  += Byte2Hex((unsigned char) S[i]);
return Result;
}

string String2Binary(const string &S)
{
const int StrLen = S.length();
string Result;

for (int i = 0; i < StrLen; ++i)
Result  += Byte2Binary(unsigned char) S[i]);
return Result;
}

0

Experts Exchange Solution brought to you by

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Commented:
char str[] = "Test string";

// Binary
for(int i = 0; i < strlen(str); ++i)
{
for(int k = 7; k >= 0; ++k)
cout << ((str[i] >> k) & 1);

cout << " ";
}
cout << endl;

// Hex
cout << setf(iob_base::hex) << str << endl;
0
Author Commented:
tinchos, print it
0
Author Commented:
tinchos, print it
0
Commented:
ok, apparently i wasa late, hope its solved
0
Author Commented:

Your code looks simple and short, what do I write that in MFC.

Thanks
0
Commented:
the code is simple, but full of problems.  (although I expect there are some syntax errors in mine too)

But 1 problem is

for(int k = 7; k >= 0; ++k)
cout << ((str[i] >> k) & 1);

nees to be

for(int k = 7; k >= 0; --k)
cout << ((str[i] >> k) & 1);

or you have an infinite (nearly) loop.

also that might work incorrectly on some systems.  You probalby better make sure the character is treated as unsigned, like

cout << ((unsigned char)(str[i] >> k) & 1);

>>cout << setf(iob_base::hex) << str << endl;
is hopeless.   the hex I/O manipulator won't work on a stringj, only numbers.  You could use it in a loop that converts each byte (character) of the string to a number (unsigned character) and then print that character in hex.  Like

for (int i = 0; i < strlen(str); ++i)
cout << hex << (unsigned char) str[i];

note also that using strlen() in the loop condition is extremely inefficient.  it makes an order N operation into an order n^2 operation.

0
Commented:
neitod,

Sorry... just early morning code :)  And yes, the strlen does add unneeded complexity to a otherwise simple function.  I thought that the

As for Bermuda, if you are using MFC you probably don't have a console window anyhow.  In that case you would need code that generates a string (or something similar) and passes it back to a function to be output in a message box or to set some window text to.  Nietod's code will work for this, and should be fairly easy to add to you app.
0
Commented:
Here are some nrealy fully tested and debuged functions, i used them myself for a converted program. But i did have to remove some logic that prevented it from converting '\r' and '\n'. Thou it uses sprintf so it will required stdio.h.

they both return a newly allocated string and free the supplied one (thou thats easy to change). so you can do whatever needs doing with the returned string

char *StrToHexStr(char *str) {
char *newstr = new char[(strlen(str)*2)+1];
char *cpold  = str;
char *cpnew  = newstr;

while('\0' != *cpold) {
sprintf(cpnew, "%02X", (char)(*cpold++));
cpnew+=2;
}
*(cpnew) = '\0';

delete [] str;
return(newstr);
}

char *StrToBinStr(char *str) {
char *newstr = new[strlen(str)*8)+1];
char *cpold  = str;
char *cpnew  = newstr;

while('\0' != *cpold) {
int  i;

for( i = 0; i < 8; i++) {
if((*cpold & mask) == 0) {
*(cpnew++) = '0';
} else {
*(cpnew++) = '1';
}

//the right shift isn't always defined
//so we must make sure the new MSB is 0 ourselves
}
cpold++;
}
*(cpnew) = '\0';

delete [] str;
return(newstr);

}
0
Commented:
using dynamic memory allocation for this is risky.  It requirs that the client pass a pointer to the start of a dynamcially allocated string, remember that the string is deleted by the function and thus any pointer that remains to the string is no longer valid, and remember to delete the strign that is returned from the function.  That is a lot of room for mistakes!  Why not use string classes that gaurantees that these sorts of mistakes are completely impossible.  They make the code nearly idiot proof.

>>  sprintf(cpnew, "%02X", (char)(*cpold++));
since cpold is defined to be a pointer to a character, there is no need to use that cast.  However on some platforms that will produce incorrect results.  You want to make sure that the character is treated as unsigned so you do need a cast, but to unsigned character.

sprintf(cpnew, "%02X", (unsigned char)(*cpold++));

>> //the right shift isn't always defined
>> //so we must make sure the new MSB is 0 ourselves
The exact behavior of the right shift is explicitly defined for an unsigned chracter.  (its implimentation defined for signed characters).  You should note that is why I used unsigned characters in my code.
0
###### It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Software

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.