#include<afx.h>
#include<iostream.h>TCHAR gBinary[][5]={ "0000" , "0001" , "0010" , "0011" , "0100" , "0101" , "0110" , "0111" , "1000" , "1001" , "1010" , "1011" , "1100" , "1101" , "1110" , "1111" };CString DecToHex(LPCTSTR lpszDec)
{
int nVal = 0;
_stscanf(lpszDec , "%d" , &nVal);
CString strHex;
strHex.Format("%X" , nVal);

return strHex;
}CString HexToBin(LPCTSTR lpszHex)
{
CString strHex(lpszHex);
CString strBinary;
    int nVal = 0;
    int i = 0;    for(i=0; i<strHex.GetLength();i++)
{
_stscanf(strHex.Mid(i,1) , "%X" , &nVal);
strBinary += gBinary[nVal];
}    return strBinary;
}void main()
{
//CString str = "255"; //decimal number 255

int nDec;
cout << endl << "Enter an decimal number: " ;
cin >> nDec;

CString strDec;

strDec.Format("%d" , nDec);

//Translate dec into hex
CString strHex = DecToHex(strDec);
//Translate hex into bin
CString strBin = HexToBin(strHex);

cout << endl << (LPCTSTR)strDec << " (dec) = " << (LPCTSTR)strHex << " (hex) = " << (LPCTSTR)strBin << " (bin)" << endl;
}

解决方案 »

  1.   

    #include <stdio.h>
    #include <mem.h>void IntToBin( int Value , char * bin )
    {
    int length = sizeof(int) * 8;
    char * str = bin;
    str[ length ] = 0;
    unsigned Mask = 1 << ( length - 1 );
    while( Mask )
    {
    if( Mask & (unsigned)Value )
    *str = '1';
    else
    *str = '0';
    str++;
    Mask >>= 1;
    }
    }void main()
    {
    char bin[ 17 ];
    IntToBin( 0xff00 , bin );
    printf( bin );
    }
      

  2.   

    #include <stdio.h>
    #include <mem.h>void IntToBin( int Value , char * bin )
    {
    int length = sizeof(int) * 8;
    char * str = bin;
    str[ length ] = 0;
    unsigned Mask = 1 << ( length - 1 );
    while( Mask )
    {
    if( Mask & (unsigned)Value )
    *str = '1';
    else
    *str = '0';
    str++;
    Mask >>= 1;
    }
    }void main()
    {
    char bin[ sizeof( int ) + 1 ];
    IntToBin( 0xff00 , bin );
    printf( bin );
    }
      

  3.   

    呵呵,怎么老贴错。#include <stdio.h>
    #include <mem.h>void IntToBin( int Value , char * bin )
    {
    int length = sizeof(int) * 8;
    char * str = bin;
    str[ length ] = 0;
    unsigned Mask = 1 << ( length - 1 );
    while( Mask )
    {
    if( Mask & (unsigned)Value )
    *str = '1';
    else
    *str = '0';
    str++;
    Mask >>= 1;
    }
    }void main()
    {
    char bin[ sizeof( int ) * 8 + 1 ];
    IntToBin( 0xff00 , bin );
    printf( bin );
    }