Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 557
Gabriel Avatar asked Jun 29 '26 08:06

Gabriel


2 Answers

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.

like image 185
Jack Lloyd Avatar answered Jun 30 '26 23:06

Jack Lloyd


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

like image 39
orlp Avatar answered Jul 01 '26 00:07

orlp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!