Link to home
Start Free TrialLog in
Avatar of BerMuDa
BerMuDa

asked on

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
Avatar of BerMuDa
BerMuDa

ASKER

correction in question:

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

print it, store it in a string ???
ASKER CERTIFIED SOLUTION
Avatar of nietod
nietod

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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;
Avatar of BerMuDa

ASKER

tinchos, print it
Avatar of BerMuDa

ASKER

tinchos, print it
ok, apparently i wasa late, hope its solved
Avatar of BerMuDa

ASKER

imadjinn,

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

Thanks
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.

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.
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) {
            char mask = (char)0x80;
            int  i;
           
            for( i = 0; i < 8; i++) {
                if((*cpold & mask) == 0) {
                    *(cpnew++) = '0';
                } else {
                    *(cpnew++) = '1';
                }

                mask = mask >> 1;

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

    delete [] str;
    return(newstr);

}
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
>> mask = mask & 0x7F;
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.