Solved

# c++: How to convert a DWORD to CHAR*?

Posted on 2006-04-21
5,437 Views
I'm trying to convert a DWORD (that is gauranteed to be populated with a numberic value) to a char*?  How would I go about doing this?

Thanks.
0
Question by:i-mate05

LVL 22

Expert Comment

do you want to convert 1234567  to  "1234567"?

or

do you want to convert 0x1828342 to a  pointer to a character at address 0x1828342?

very different things.
0

Author Comment

I'm looking to convert 123456789 to "123456789".
0

LVL 22

Accepted Solution

int TheNum; char Out[1000];

TheNum = 123456789;

sprintf( Out, "%d", TheNum );
0

Author Comment

Is there a way to get the actual size of the int so the char length is exact?
0

LVL 25

Expert Comment

Perhaps something like

DWORD i = 123456789 ;
int size = int(i/10)+1 ;
0

LVL 1

Expert Comment

Hi,

This is primitive and there is probably a better way to find the number of numbers in a number...heh, but you could try this:

int length = 0;
int num = 1500;

while( num > 0 )
{
num /= 10;
length ++;
}

// length now equals 4

Regards,
choo_chu
0

LVL 22

Expert Comment

Dividing by ten is a good way, if a bit slow.

an alternative way, a bit faster but less precise, would be to divide by two (by bit shifting), then multiply the resulting count by log10(2),  or is it log2(10)?

or just take ceiling( log10(num) ) + 1 and that shoul dbe close enough.

0

LVL 9

Expert Comment

what about negative numbers and zero?

int x = crap;

bool y = x<0;
if ( y )
length = ceiling( log10(num) ) + 2;
else if ( !x )
length = 1;
else
length = ceiling( log10(num) ) + 1;
0

LVL 12

Expert Comment

>> Is there a way to get the actual size of the int so the char length is exact?
Use stringstream. You don't have to specify the size then.

#include <sstream>
#include <iostream>
...
DWORD dword = 123456789;
std::stringstream stream;
stream << dword;
std::string str = stream.str();
std::cout << str << std::endl;

If you want the char* then do this

char* cPtr = str.c_str();
0

## Featured Post

When writing generic code, using template meta-programming techniques, it is sometimes useful to know if a type is convertible to another type. A good example of when this might be is if you are writing diagnostic instrumentation for code to generat…
IntroductionThis article is the second in a three part article series on the Visual Studio 2008 Debugger.  It provides tips in setting and using breakpoints. If not familiar with this debugger, you can find a basic introduction in the EE article loc…
The goal of the video will be to teach the user the concept of local variables and scope. An example of a locally defined variable will be given as well as an explanation of what scope is in C++. The local variable and concept of scope will be relat…
The viewer will learn how to clear a vector as well as how to detect empty vectors in C++.

#### Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!