简体   繁体   中英

Converting std::string into hex, and then storing it in a byte array

This question probably has an easy answer. I believe I have some working code, but I feel like there is a much better solution.

In any case, this is the problem I'm having:

Basically a user enters some data into a terminal, and my program is monitoring the terminal. It's important to know that I'm not using cin , which I know can easily be manipulated to interpret incoming data as hexadecimal. Instead, my program is using an adapted version of conios.h for linux and using kbhit() . All user input is stored as a std::string until the user decides to submit it.

At that point, I have to interpret the string as hexadecimal - but there's a minor caveat. I have to save this string in a character array.

That said, this is what I have:

     ...
     char bufferBytes[6144];
     std::string bufferString = "";
     ...

     for(i = 0; i < bufferString.length(); i = i+2)
     {
        bufferBytes[i] = (stoi(bufferString.at(i), 0, 16) << 4);
        bufferBytes[i] = (stoi(bufferString.at(i+1), 0, 16);    
     }

I believe this will do the trick, but I feel like there's probably a better solution.

Any input would be appreciated.

EDIT:

Say a user enters 0123456789ABCDEF . This is stored as a std::string until the user decides to submit it. At this point, I need to interpret this std::string as hexadecimal numbers and store them in a character array. I believe the code I have above will work, but is there a better/more efficient way of doing what I described.

Here's a rough snippet that would probably do the job.

  for (int i = 0; i < bufferString.length(); i += 2) {

    bufferBytes[i/2] = (bufferString[i] - '0') << 4;
    bufferBytes[i/2] |= bufferString[i+1] - '0';

  }

If your intention is to store each hex digit as their own char element then this should be the body of the loop:

    bufferBytes[i] = (bufferString[i] - '0') << 4;
    bufferBytes[i+1] = bufferString[i+1] - '0';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM