How to convert DWORD to int?

Hello everybody...
Currently I got a trouble about how to convert a DWORD (unsigned int) value from a string to a regular integer value. I could not find anything which is related to string -> DWORD -> int -> char etc... Atoi & atof can't help me because they can't do this, they don't understand the hex value, Here's the example :
 
char *dw = "0xFDE390";
unsigned int dword = Convert(dw);


Is there any trick, method or function which can do this?
I'm looking forward to your help.
Thanks you.
Last edited on
You can use std::stoul if you want to get an unsigned value.
EDIT: Oh, I am sorry. I am wrong.

Try the following

1
2
3
4
5
6
7
8
9
const char *dw = "0xFDE390";

std::istringstream is( dw );

unsigned int x;

is >> std::hex >> x;

std::cout << std::hex << "x = " << x << std::endl;


EDIT: And again I was wrong. The code above is correct. But you can use std::stoul as I said the first time

1
2
unsigned long y = std::stoul( dw, 0, 16 );
std::cout << std::hex << "y = " << y << std::endl;


So you can use either the function or the input string stream.:)
Last edited on
Note that std::stoul is a C++11 feature. But there is also the older strtoul function for older versions of C++

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

unsigned long int strtoul ( const char * str, char ** endptr, int base );

With strtoul you can also pass 0 as the base (the last param). strtoul (but not stoul) will then treat anything with a 0x prefix as hex. (The default for base for stoul is 10, but I haven't tried passing 0 to it...)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <cstring>

int main()
{
	const char* dec = "123";
	const std::string hex = "0xFDE390";

	// use 0 as base to strtoul works base out for itself
	unsigned long x = std::strtoul( dec, NULL, 0 );
	unsigned long y = std::strtoul( hex.c_str(), NULL, 0 );
	// as stoul takes a const std::string&, rather than a const char*, 
	// there is no need for c_str() if it's used instead of strtoul

	std::cout << std::showbase;
	std::cout << "x = " << x << std::endl;
	std::cout << std::hex << "y = " << y << std::endl;

	return 0;
}


x = 123
y = 0xfde390

Andy

PS There's no cplusplus.com entry for stoul at the mo, but there is this:

std::stoul, std::stoull
http://en.cppreference.com/w/cpp/string/basic_string/stoul

unsigned long stoul( const std::string& str, size_t *pos = 0, int base = 10 );
Last edited on
You can also take this as a programming challenge, and try to workout your own function that can convert a hexadecimal string into a unsigned int. That will give you some experience with handling strings.

Regards,

Simon H.A.
Topic archived. No new replies allowed.