开发者

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


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.


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.


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.


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜