Dan Snyder
Dan Snyder

Reputation: 1519

Convert ASCII string into Decimal and Hexadecimal Representations

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;
}

Upvotes: 0

Views: 12187

Answers (5)

Anonymous Coward
Anonymous Coward

Reputation: 1

#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;
}

Upvotes: 0

brennie
brennie

Reputation: 543

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.

Upvotes: 1

Puppy
Puppy

Reputation: 146920

for(int i = 0; i < string.size(); i++) {
    std::cout << std::hex << (unsigned int)string[i];
}

Upvotes: 0

Jerry Coffin
Jerry Coffin

Reputation: 490128

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.

Upvotes: 6

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272497

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.

Upvotes: 3

Related Questions