Tutorial :Convert ASCII string into Decimal and Hexadecimal Representations



Question:

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


Solution: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.


Solution:2

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.


Solution: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.


Solution:4

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


Solution:5

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »