■ 問題提出
MFC自帶函數(shù)_ultot(int ivalue, TCHAR* szBuf, int radix);可以將整數(shù)轉(zhuǎn)換為16進(jìn)制。不過使用這個(gè)函數(shù)有個(gè)問題就是如果16進(jìn)制的高位為零的時(shí)候,就自動(dòng)忽略。
比如
WORD wL = 0x3;
TCHAR szStandard[5];
_itot(wL,szStandard, 2);
szStandard的結(jié)果是“11”,跟我想要的“0011”有點(diǎn)差距。
查來查去的又浪費(fèi)時(shí)間,還是自己寫轉(zhuǎn)換函數(shù)吧。嘿嘿
■ 簡單要求(式樣):
輸入:整數(shù)Byte,有效位為低4位。
輸出:TCHAR* 指向的數(shù)組。要求輸出的值為“xxxx”格式。注意格式不是“xxxx xxxx”。因?yàn)槲倚枰?/span>Byte每次只是轉(zhuǎn)換低4Bit。
■ 函數(shù)實(shí)現(xiàn)代碼:
void _byte_to_bitstr(BYTE cValue, LPTSTR lpszBuf)
{
if ( lpszBuf == NULL )
return ;
int x = 0;
int radix = 2;
BYTE cTmpValue = cValue & 0x0F; // Only calc the low 4 Bit
while(cTmpValue)
{
cTmpValue /= radix;
if (cTmpValue)
x++;
}
for(int i = 0; i < 4; i++) // result must be 0000 ~ 1111 !!
{
lpszBuf[i] = L'0';
}
lpszBuf[4] = L'\0';
int iIndex = 3;
while( x >= 0 )
{
const int v = cValue % radix;
if (v > 10)
lpszBuf[iIndex] = 'a' + v - 10;
else
lpszBuf[iIndex] = '0' + v;
iIndex--;
cValue /= radix;
x--;
}
}
■ 測試:
TCHAR szBuf[5];
BYTE cValue = 0x3;
_byte_to_bitstr (cValue, szBuf);
■ 應(yīng)用
給定一個(gè)WORD wValue = 0xcc33;可以得到字符串。
“1100 1100 0011 0011”
WORD wValue = 0xcc33;
CString strValue;
BYTE cValue;
TCHAR szBitArray3[5];
TCHAR szBitArray2 [5];
TCHAR szBitArray1 [5];
TCHAR szBitArray0 [5];
cValue = HIBYTE(wValue);
_byte_to_bitstr ((cValue >> 4) & 0x0F, szBitArray3);
_byte_to_bitstr ((cValue & 0x0F ), szBitArray2);
cValue = LOBYTE(wValue);
_byte_to_bitstr ((cValue >> 4) & 0x0F, szBitArray1);
_byte_to_bitstr (cValue & 0x0F , szBitArray0);
strValue.Format(_T("%s %s %s %s"), szBinary3, szBinary2, szBinary1, szBinary0);