Gabriel
Gabriel

Reputation: 1443

Convert from std::string to DWORD


I have a simple problem with a conversion:

std::string str = "0xC0A80A02"

and I need to convert it to DWORD.
I searched on the web and found some solution but none seems to work.
try1:

DWORD m_dwIP = atol(str.c_str());

try2:

std::istringstream ss(str.c_str());
ss >> m_dwIP;

try3:

sscanf (str.c_str(),"%u",str,&m_dwIP);

Note the string stores the value in hexa .

Thanks,
Gabriel

Upvotes: 3

Views: 24226

Answers (3)

Jack Lloyd
Jack Lloyd

Reputation: 8405

istringstream will work fine, just strip off the 0x prefix and use the std::hex formatter:

  std::string str = "0xC0A80A02";
  unsigned int m_dwIP;

  std::istringstream ss(&str[2]);
  ss >> std::hex >> m_dwIP;

  std::cout << std::hex << m_dwIP << "\n";

Outputs c0a80a02.

Upvotes: 8

orlp
orlp

Reputation: 117681

Assuming sizeof(DWORD) == sizeof(unsigned long), this should do:

#include <cstdlib>
DWORD m_dwIP = std::strtoul(str.c_str(), NULL, 16);

See http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/.

Note that this is usable for both C and C++ (strip of the std:: and c_str() and change <cstdlib> to <stdlib.h> but this should be pretty obvious).

Upvotes: 7

NVade
NVade

Reputation: 278

This is a fairly straightforward problem. How would you, as a person, read that hexadecimal number and convert it to decimal? If you are superhuman, you will just know it immediately, but if you are like the rest of us and use valuable brain space to remember non-computer things like how to swing a golf club, you'll have to do some arithmetic. You'd use a mental algorithm to do the conversion, and what you need is code that does the thinking for you. You can use this algorithm:

  1. initialize an accumulator variable to 0
  2. initialize a multiplier variable to 1
  3. loop from the END of the string until you reach the beginning of the number (the 'x' char in your case)
  4. for each char, take the hex value of the char (0-9 for 0-9, 10-15 for a-f) and multiply it by the multiplier, and add it to the accumulator
  5. multiply your accumulator by 16 (or be cool and just shift to the left 4 bits)
  6. repeat back to #3 until you finish all the digits

When you are all done, the value left in your accumulator is your result.

Upvotes: -3

Related Questions