-
October 2nd, 2002, 12:51 PM
#1
Convert a DWORD to a binary string?
I've got a DWORD I need to convert to a binary string (char array of 1's and 0's). Problem is, I'm not a VC++ programmer, and am stumbling my way through this. Is there an easy way to do this conversion?
Code:
#include "stdafx.h"
#include <windows.h>
int main(int argc, char* argv[])
{
DWORD drives;
drives = GetLogicalDrives();
printf("Drives: %d\n", drives);
return 0;
}
-
October 2nd, 2002, 12:58 PM
#2
PHP Code:
int main()
{
DWORD dwTemp = 0x3AF1;
WORD low = LOWORD(dwTemp);
WORD high = HIWORD(dwTemp);
char szLow[10];
char szHigh[10];
char szString[32];
WordToBinaryAscii(szLow,low,8);
WordToBinaryAscii(szHigh,high,8);
//this might be the other way around, I forgot
strcpy(szString, szLow);
strcat(szString, szHigh);
//Should print out 0011101011110001
cout<<szString <<endl;
return 0;
}
int WordToBinaryAscii(char* dst, WORD wd, int len)
{
int charOffset = 0;
int wdAmt;
for(int x = 0; x < len; x++)
dst[x] = '0';
while((len > 0) && (wd >= 0))
{
wdAmt = (int)pow(2, --len);
if(wd - wdAmt >= 0)
{
wd -= wdAmt;
dst[charOffset] = '1';
}
else
dst[charOffset] = '0';
charOffset++;
}
dst[charOffset] = 0x00;
return charOffset;
}
-
October 2nd, 2002, 01:08 PM
#3
Thanks!
-
October 2nd, 2002, 01:14 PM
#4
Another method using bitset ...
Code:
#include <windows.h>
#include <iostream>
#include <bitset>
#include <string>
int main()
{
DWORD dwValue = 0x3AF1;
std::bitset<32> bits((unsigned long)dwValue);
std::cout << bits << std::endl;
std::string str(bits.to_string()); // convert to std::string()
std::cout << str << std::endl;
return 0;
}
-
October 2nd, 2002, 01:20 PM
#5
Don't thank him yet, that was sloppy.
In Win32, a WORD is 16-bits and a DWORD is 32-bits, so those character buffers need to be larger. The lines where he puts the string together are backwards as well.
int main()
{
unsigned int dwTemp = 0x3AF1;
WORD low = LOWORD(dwTemp);
WORD high = HIWORD(dwTemp);
char szLow[17];
char szHigh[17];
char szString[33];
WordToBinaryAscii(szLow,low,16);
WordToBinaryAscii(szHigh,high,16);
//yes, this was the other way around
strcpy(szString, szHigh);
strcat(szString, szLow);
//Should print out 0011101011110001
cout<< szString <<endl;
return 0;
}
-
October 2nd, 2002, 01:23 PM
#6
Originally posted by Pug
Don't thank him yet, that was sloppy.
It was just an example. Why not contribute for a while before trying to set me on fire.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|