Solved

# Convert a string to Binary & hexadecimal value

Posted on 2003-02-22
Medium Priority
69,911 Views
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
0
Question by:BerMuDa
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 4
• 3
• 2
• +2

Author Comment

ID: 7999336
correction in question:

Is there a way to convert a string "ASCII" to its *Binary* & hexadecimal value.
0

LVL 9

Expert Comment

ID: 7999385
where do you want to store the result

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

LVL 22

Accepted Solution

nietod earned 240 total points
ID: 7999407

#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

LVL 1

Expert Comment

ID: 7999411
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 Comment

ID: 7999433
tinchos, print it
0

Author Comment

ID: 7999457
tinchos, print it
0

LVL 9

Expert Comment

ID: 7999473
ok, apparently i wasa late, hope its solved
0

Author Comment

ID: 7999518

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

Thanks
0

LVL 22

Expert Comment

ID: 8000575
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

LVL 1

Expert Comment

ID: 8000759
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

Expert Comment

ID: 8000902
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

LVL 22

Expert Comment

ID: 8001086
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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In our personal lives, we have well-designed consumer apps to delight us and make even the most complex transactions simple. Many enterprise applications, however, are a bit behind the times. For an enterprise app to be successful in today's tech woâ€¦
Container Orchestration platforms empower organizations to scale their apps at an exceptional rate. This is the reason numerous innovation-driven companies are moving apps to an appropriated datacenter wide platform that empowers them to scale at a â€¦
Monitoring a network: why having a policy is the best policy? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the enormous benefits of having a policy-based approach when monitoring medium and large networks. Software utilized in this vâ€¦
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (httpsâ€¦
###### Suggested Courses
Course of the Month12 days, 10 hours left to enroll