0

I need to convert an ASCII string like... "hello2" into it's decimal and or hexadecimal representation (a numeric form, the specific kind is irrelevant). So, "hello" would be : 68 65 6c 6c 6f 32 in HEX. How do I do this in C++ without just using a giant if statement?

EDIT: Okay so this is the solution I went with:

int main()
{
    string c = "B";
    char *cs = new char[c.size() + 1];
    std::strcpy ( cs, c.c_str() );
    cout << cs << endl;

    char a = *cs;
    int as = a;
    cout << as << endl;
    return 0;
}
Dan Snyder
  • 1,483
  • 7
  • 20
  • 29
  • you can implictly convert any char to its ascii value by doing `char a = 'B'; int as = a;` <- yields 66 (the ascii value) –  Aug 03 '10 at 20:00
  • I like this trick. My only question now is, how do I convert a string in this way? I guess the question really is, how do I equate a single element of a string to "a"? – Dan Snyder Aug 03 '10 at 20:56
  • You can do it in a for loop, character by character. –  Aug 04 '10 at 00:15

5 Answers5

6

Just print it out in hex, something like:

for (int i=0; i<your_string.size(); i++)
    std::cout << std::hex << (unsigned int)your_string[i] << " ";

Chances are you'll want to set the precision and width to always give 2 digits and such, but the general idea remains the same. Personally, if I were doing it I'd probably use printf("%.2x");, as it does the right thing with considerably less hassle.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
  • @0A0D:missing reasonable excuse for downvote. The question already gives an example of both the input and the output. I'm just telling him how to get it. – Jerry Coffin Aug 03 '10 at 20:08
  • "hello2" into it's decimal and or hexadecimal representation" - seems clear to me he wants decimal and hexadecimal. –  Aug 03 '10 at 20:14
  • @0A0D: That's what docs are for. He could add a link to docs if he wanted to "complete" the answer. The point is that he gave him a pointer to the string formatting options in iostreams. – Merlyn Morgan-Graham Aug 03 '10 at 20:25
3

A string is just an array of chars, so all you need to do is loop from 0 to strlen(str)-1, and use printf() or something similar to format each character as decimal/hexadecimal.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 3
    @DeadMG: C is still valid C++ –  Aug 03 '10 at 19:49
  • Even in C++, and every language out there, when you boil it all down, a string is just an array of chars. – corsiKa Aug 03 '10 at 19:52
  • Technically, that code is valid C++. But then, so is *NULL, and I would downvote you for that, too. strlen won't take std::strings, and nor will printf. That makes your code invalid for any normal C++ program, and bad advice. C-strings should be avoided like the plague. – Puppy Aug 03 '10 at 20:00
  • @DeadMG: Why would a function designed for C strings take a std::string? There is nothing wrong with C strings when they are used properly (such as strncpy vs strcpy) –  Aug 03 '10 at 20:03
  • @DeadMG: "hello2" is a string literal; the OP said nothing about `std::string`. As others have pointed out, using `printf()` is considerably less verbose than C++ stream formatting. – Oliver Charlesworth Aug 03 '10 at 20:09
1

You can use printf() to write the result to stdout or you could use sprintf / snprintf to write the result to a string. The key here is the %X in the format string.

#include <cstdio>
#include <cstring>
int main(int argc, char **argv)
{
    char *string = "hello2";
    int i;

    for (i = 0; i < strlen(string); i++)
        printf("%X", string[i]);

    return 0;
}

If dealing with a C++ std::string, you could use the string's c_str() method to yield a C character array.

brennie
  • 543
  • 1
  • 3
  • 12
  • Missing string to ASCII value example –  Aug 03 '10 at 20:04
  • String to ASCII value example? The poster states that he starts with an ASCII value. "I need to convert an ASCII string like... "hello2"" – brennie Aug 03 '10 at 20:12
  • "hello2" into it's decimal and or hexadecimal representation" - seems clear to me he wants decimal and hexadecimal. –  Aug 03 '10 at 20:14
  • @0A0D the key phrase is "and or" which I assume means "and/or." The key word here is "or." – brennie Aug 03 '10 at 20:18
0
for(int i = 0; i < string.size(); i++) {
    std::cout << std::hex << (unsigned int)string[i];
}
Puppy
  • 144,682
  • 38
  • 256
  • 465
  • doesn't work on my compiler (I think the cast is needed, though I'm wondering why). – KeatsPeeks Aug 03 '10 at 19:52
  • What's the error? Builds fine on my compiler- although the cast is needed to get hex. – Puppy Aug 03 '10 at 19:58
  • Because `operator<<` is overloaded, and you need the overload that takes an `int` (or `short`, `long`, etc.) for the `hex` flag to have an effect (i.e., the overload for `char` ignores the `hex` flag). – Jerry Coffin Aug 03 '10 at 19:58
0
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>

int main() {
  std::string hello = "Hello, world!";

  std::cout << std::hex << std::setw(2) << std::setfill('0');
  std::copy(hello.begin(),
            hello.end  (),
            std::ostream_iterator<unsigned>(std::cout, " "));
  std::cout << std::endl;
}