Ardy
Ardy

Reputation: 3

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 decimal value.

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

Upvotes: 0

Views: 21756

Answers (4)

Eugene
Eugene

Reputation: 7258

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++.

Upvotes: 0

Monkey
Monkey

Reputation: 1866

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

Upvotes: 1

Charles Salvia
Charles Salvia

Reputation: 53289

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

Upvotes: 4

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

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.

Upvotes: 0

Related Questions