Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6075
  • Last Modified:

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

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
i-mate05
Asked:
i-mate05
1 Solution
 
grg99Commented:
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
 
i-mate05Author Commented:
I'm looking to convert 123456789 to "123456789".
0
 
grg99Commented:
int TheNum; char Out[1000];

TheNum = 123456789;

sprintf( Out, "%d", TheNum );
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
i-mate05Author Commented:
Is there a way to get the actual size of the int so the char length is exact?
0
 
InteractiveMindCommented:
Perhaps something like


DWORD i = 123456789 ;
int size = int(i/10)+1 ;
0
 
choo_chuCommented:
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
 
grg99Commented:
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
 
jhshuklaCommented:
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
 
rajeev_devinCommented:
>> 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

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now