1、CString转char*
char* CString2Char(CString msg)
{
char* fName;
LPCTSTR p = msg.GetBuffer(0);
msg.ReleaseBuffer();
fName = new char [msg.GetLength()+1];
strcpy_s(fName,msg.GetLength()+1, CT2CA(p));
return fName;
}
2、char*转CString
CString Char2CString(char* cData)
{
int charLen = strlen(cData);
//计算多字节字符的大小,按字符计算。
int len = MultiByteToWideChar(CP_ACP,0,cData,charLen,NULL,0);
//为宽字节字符数组申请空间,数组大小为按字节计算的多字节字符大小
wchar_t *buf = new wchar_t[len + 1];
//多字节编码转换成宽字节编码
MultiByteToWideChar(CP_ACP,0,cData,charLen,buf,len);
buf[len] = '\0';
//将TCHAR数组转换为CString
CString pWideChar(buf);
delete []buf;
return pWideChar;
}
3、char*转16进制字符串
CString Char2HexCString(char* cData,int len)
{
CString sHex;
CString sTemp;
for (int i =0;i < len;i++)
{
sTemp.Format("%02X",cData[i]);
sHex += sTemp.Right(2);
sHex += " ";
}
return sHex;
}
4、unicode转换为utf8
/*功能:unicode转换为utf8编码
输入:unicode类型的字符串
输出:utf8类型的char*型数据
*/
char* UnicodeToUtf8(char* unicode)
{
int len = WideCharToMultiByte(CP_UTF8, 0, (LPCWSTR)unicode, -1, NULL, 0, NULL, NULL);
char *szUtf8=new char[len + 1];
memset(szUtf8, 0, len + 1);
WideCharToMultiByte (CP_UTF8, 0, (LPCWSTR)unicode, -1, szUtf8, len, NULL,NULL);
szUtf8[len]= '\0';
len=len-1;
return szUtf8;
}
5、utf8转换为unicode
/*功能:utf8转换为unicode编码
输入:utf8类型的字符串
输出:unicode类型的char*型数据
*/
WCHAR * Utf8ToUnicode(char* unicode)
{
int len = MultiByteToWideChar(CP_UTF8, 0, unicode, -1, NULL, 0);
WCHAR *szUtf8=new wchar_t[len + 1];
memset(szUtf8, 0, len + 1);
MultiByteToWideChar (CP_UTF8, 0, unicode, -1, szUtf8, len);
szUtf8[len]= '\0';
len=len-1;
return szUtf8;
}
6、二进制CString转WORD
WORD Binary2CString (CString ss)
{
WORD decv = 0;
float two = 2;
for (int i = 0;i < ss.GetLength();i++)
{
if (ss[i] == '1')
{
decv += WORD(pow(two,(ss.GetLength()-1-i)));
}
}
return decv;
}
7、二进制字符串转换成十进制。
int Binary2Int (CString binaryString)
{
long nDec = 0, nLen;
int i, j, k;
nLen = binaryString.GetLength();
for (i=0; i<nLen; i++)
{
if ( binaryString[nLen-i-1] == '0' )
{
continue;
}
else
{
k = 1;
for(j=0; j<i; j++)
{
k = k * 2;
nDec += k;
}
}
}
return nDec;
}
8、int转byte
public byte[] int2ByteArray(int i)
{
byte[] result=new byte[4];
result[0]=(byte)((i >> 24)& 0xFF);
result[1]=(byte)((i >> 16)& 0xFF);
result[2]=(byte)((i >> 8)& 0xFF);
result[3]=(byte)(i & 0xFF);
return result;
}
9、ASCII字符串转16进制字符串
CString ASCII2Hex(CString str_ASCII)
{
int i;
int length = str_ASCII.GetLength();
CString str_HEX;
CString temp;
for (i=0; i<length; i++)
{
temp.Format(_T("%d "), str_ASCII.GetAt(i));
str_HEX = str_HEX + temp;
}
return str_HEX;
}
10、byte[ ]转int
public int bytes2Int(byte[] bytes)
{
int num=bytes[3] & 0xFF;
num |=((bytes[2] <<8)& 0xFF00);
num |=((bytes[1] <<16)& 0xFF0000);
num |=((bytes[0] <<24)& 0xFF0000);
return num;
}