建议使用bitset! Example // bitset_to_ulong.cpp // compile with: /EHsc #include <bitset> #include <iostream>int main( ) { using namespace std; bitset<5> b1 ( 7 ); cout << "The ordered set of bits in the bitset<5> b1( 7 )" << "\n that was generated by the number 7 is: ( " << b1 << " )" << endl; unsigned long int i; i = b1.to_ulong( ); cout << "The integer returned from the bitset b1," << "\n by the member function to_long( ), that" << "\n generated the bits as a base two number is: " << i << "." << endl; } Output The ordered set of bits in the bitset<5> b1( 7 ) that was generated by the number 7 is: ( 00111 ) The integer returned from the bitset b1, by the member function to_long( ), that generated the bits as a base two number is: 7.
CHAR chBuf[] = {"01001010"};for (INT i = 0; i < 8; ++i)
{
if (chBuf[i] == '1')
{
nIndex<<1;
}
}
{
int nLength = strBinary.GetLength();
CString str = strBinary;
//位数不是四的倍数时补齐
switch(nLength%4)
{
case 0:
break;
case 1:
strBinary.Format("%d%d%d%s",0,0,0,str);
break;
case 2:
strBinary.Format("%d%d%s",0,0,str);
break;
case 3:
strBinary.Format("%d%s",0,str);
break;
default:
return "";
break;
}
CString strHex,str1;
str1 = "";
nLength = strBinary.GetLength();
for(int i=1;i<=(nLength/4);i++)
{
//每四位二进制数转换为一十六进制数
str = strBinary.Left(4);
CString strDecimal = BinaryToDecimal(str);
int nDecimal = atoi(strDecimal.GetBuffer(0));
if(nDecimal<10)
str1.Format("%d",nDecimal);
else
{
char c = 'A' + (nDecimal-10);
str1.Format("%c",c);
}
strHex += str1;
strBinary = strBinary.Right(strBinary.GetLength()-str.GetLength());
}
return strHex;
}
BYTE lpData = lpSrc; for (INT i = 0; i < 8; ++i)
{
nIndex = nIndex<<1;
if ('1' == lpData [i])
{
nIndex += 1;
} }
to :lixiaosan(小三) ( )
CString strDecimal = BinaryToDecimal(str);
是什么啊,我怎么在MSDN上找不到啊?
{
int nLenth = strBinary.GetLength();
char* Binary = new char[nLenth];
Binary = strBinary.GetBuffer(0);
int nDecimal = 0;
for(int i=0;i<nLenth;i++)
{
char h = Binary[nLenth-1-i];
char str[1];
str[0] = h;
int j = atoi(str);
for(int k=0;k<i;k++)
{
j=j*2;
}
nDecimal += j;
}
CString strDecimal;
strDecimal.Format("%d",nDecimal);
return strDecimal;
}
Example
// bitset_to_ulong.cpp
// compile with: /EHsc
#include <bitset>
#include <iostream>int main( )
{
using namespace std; bitset<5> b1 ( 7 ); cout << "The ordered set of bits in the bitset<5> b1( 7 )"
<< "\n that was generated by the number 7 is: ( "
<< b1 << " )" << endl; unsigned long int i;
i = b1.to_ulong( );
cout << "The integer returned from the bitset b1,"
<< "\n by the member function to_long( ), that"
<< "\n generated the bits as a base two number is: "
<< i << "." << endl;
}
Output
The ordered set of bits in the bitset<5> b1( 7 )
that was generated by the number 7 is: ( 00111 )
The integer returned from the bitset b1,
by the member function to_long( ), that
generated the bits as a base two number is: 7.
for(i = 0;i<n;i++)
if(lpSrc[i]=='1')
{
lpDev[i/8] = 1<<(i%8)
}
因为 D=8+4+0+1