String to Hexadecimal conversion (help!)

Post your questions, suggestions and experiences regarding game design, integration of external libraries here. For irrEdit, irrXML and irrKlang, see the
ambiera forums
Post Reply
cobra
Posts: 371
Joined: Fri Jan 23, 2009 2:56 am
Location: United States
Contact:

String to Hexadecimal conversion (help!)

Post by cobra »

Hi guys. I need to convert a string to a hexadecimal char.

I am currently trying this:

Array of characters and hexadecimal units:

Code: Select all

string letters[95] = {" ","!","\"","#","$","%","&","'","(",")","*","+",",","-",
                     ".","/","0","1","2","3","4","5","6","7","8","9",":",";","<",
                     "=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N",
                     "O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_",
                     "'","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p",
                     "q","r","s","t","u","v","w","x","y","z","{","|","}","~"};

string hexadecimals[95] = {"20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D",
                     "2E","2F","30","31","32","33","34","35","36","37","38","39","3A","3B","3C",
                     "3D","3E","3F","40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E",
                     "4F","50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
                     "60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F","70",
                     "71","72","73","74","75","76","77","78","79","7A","7B","7C","7E","7F"};

Then I try to convert them like this:

Code: Select all

char *charToHex(string st)
{
    char *hex = "";
    hex = new char[st.length()];


    for(unsigned int i=0; i<95; i++)
    {
        if(st.find(letters[i]) !=string::npos)
        {
            st = ReplaceAllG(st, letters[i], hexadecimals[i]);
        }
    }

    strcpy(hex, st.c_str());
    return hex;
    delete[] hex;
}

It all works fine unless there is an integer or other non-letter character such as $, %, #, and ;.

Any idea WHY it does this? It's driving me insane, I've looked over it several times and tried new solutions, to no avail.

Also, instead of using that way, I also tried this:

Code: Select all

for(unsigned int i=0; i<95; i++)
    {
        pos = st.find(letters[i]);
        if(pos != string::npos)
            st.replace(pos, 1, hexadecimals[i]);
            pos += 2;*/
    }
Which replaces them fine, except it only does it for one instance. I need to replace all occurences of the found character.

This should be simple, but for some reason the ways I'm doing it aren't working. Any ideas, or a better way to do it? thanks..[/code]
Josiah Hartzell
Image
Seven
Posts: 1034
Joined: Mon Nov 14, 2005 2:03 pm

Post by Seven »

out of curiosity, why are you trying to do this?
wITTus
Posts: 167
Joined: Tue Jun 24, 2008 7:41 pm
Location: Germany

Post by wITTus »

Code: Select all

#include <string>
#include <sstream>
#include <iostream>
 
int main() {
        std::string Test("Yo. Test! #§%\"%)(/");
        std::string Result;

        std::string::const_iterator it = Test.begin();

        for (; it != Test.end(); ++it) {
                std::stringstream ss;
                std::string Tmp;

                ss << std::hex << static_cast<unsigned int>(static_cast<unsigned char>((*it)));
                ss >> Tmp;
                Result += Tmp;
        }  
        std::cout << Test << std::endl;
        std::cout << Result << std::endl;
}

Code: Select all

wittus@hell ~ $ ./test 
Yo. Test! #§%"%)(/
596f2e2054657374212023c2a725222529282f
lol, maybe you should switch to C++. Just kidding :wink:
Generated Documentation for BlindSide's irrNetLite.
"When I heard birds chirping, I knew I didn't have much time left before my mind would go." - clinko
vitek
Bug Slayer
Posts: 3919
Joined: Mon Jan 16, 2006 10:52 am
Location: Corvallis, OR

Post by vitek »

There are lots of problems with the original code. The code above is also terribly inefficient.

If you just want to convert a string to its hex representation, the following C++ code sould work...

Code: Select all

#include <sstream>
#include <string>

std::string to_hex(const std::string& s)
{
  std::ostringstream os;
  os.setf (std::ios::hex, std::ios::basefield);

  for (std::string::const_iterator it = s.begin(); it != s.end(); ++it)
  {
    os << int(*it);
  }

  return os.str();
}
If you don't want to use the C++ standard library, you could use the C standard library...

Code: Select all

#include <stdio.h>

const char* to_hex(const char* s, size_t n, char* ss, size_t nn)
{
  size_t j = 0;
  for (size_t i = 0; i < n; ++i)
  { 
    int c = snprintf (ss + j, nn - j, "%hhx", s [i]);
    if (c < 2)
      return 0;

    j += c;
    if ((nn - j) < 1)
      return 0;
  }

  ss [j] = 0;

  return ss;
}
Of course both of the above snippets will give different results on systems that use a non-ascii character set. You can avoid that by using a lookup table.

Travis
cobra
Posts: 371
Joined: Fri Jan 23, 2009 2:56 am
Location: United States
Contact:

Post by cobra »

Thanks for your replies, and thanks to Vitek for the solution! I didn't think it was that easy. :)

@Seven: The reason I need to do this, is because I'm also programming a network extension program aside from my main project, that extends the online capabilities of a free flight simulator. The TCP packets are encoded in hexadecimal characters.

Also, Vitek, could you give me a snippet to convert hex to ascii please?

Sorry, my time is mainly at my FTW project but partly at the extension, so once I figure this out, there isn't much other hassle to it since I can read and write packets to send/receive. Thanks. :)
Josiah Hartzell
Image
wITTus
Posts: 167
Joined: Tue Jun 24, 2008 7:41 pm
Location: Germany

Post by wITTus »

Vitek, your function yields to "c2ffffff" for '#'. Mine is better. :twisted:
Generated Documentation for BlindSide's irrNetLite.
"When I heard birds chirping, I knew I didn't have much time left before my mind would go." - clinko
Post Reply