开发者

How to convert ASCII string to hexadecimal?

I have tried to find this topic on the web but I couldn't find the one I need.

I have a string of character:

char * tempBuf = "qj";

The result I want is 0x716A, and that value is going to be converted into deci开发者_如何学编程mal value.

Is there any function in vc++ that can be used for that?


You can use a stringstream to convert each character to a hexadecimal representation.

#include <iostream>
#include <sstream>
#include <cstring>

int main()
{
    const char* tempBuf = "qj";

    std::stringstream ss;

    const char* it = tempBuf;
    const char* end = tempBuf + std::strlen(tempBuf);

    for (; it != end; ++it)
        ss << std::hex << unsigned(*it);

    unsigned result;
    ss >> result;

    std::cout << "Hex value: " << std::hex << result << std::endl;
    std::cout << "Decimal value: " << std::dec << result << std::endl;
}


So if I understood correctly the idea...

  #include <stdint.h>

  uint32_t charToUInt32(const char* src) {
    uint32_t ret = 0;
    char* dst = (char*)&ret;
    for(int i = 0; (i < 4) && (*src); ++i, ++src)
      dst[i] = *src;

    return ret;
  }


If I understand what you want correctly: just loop over the characters, start to finish; at each character, multiply the sum so far by 256, and add the value of the next character; that gives the decimal value in one shot.


What you are looking for is called "hex encoding". There are a lot of libraries out there that can do that (unless what you were looking for was how to implement one yourself).

One example is crypto++.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜