16,472
社区成员
发帖
与我相关
我的任务
分享
BYTE Char2Bin(char ch)
{
BYTE b = 0;
if(ch >= '0' && ch <= '9')
{
b = ch - '0';
}
else if(ch >= 'a' && ch <= 'f')
{
b = ch - 'a' + 10;
}
else if(ch >= 'A' && ch <= 'F')
{
b = ch - 'A' + 10;
}
else
{
ASSERT(FALSE);
}
return b;
}
void Test()
{
LPCSTR sSrc = "0123456789abcdef";
int iSrcLen = strlen(sSrc);
for(int i=0; i<iSrcLen-4; i+=4)
{
USHORT sVal = 0;
sVal <<= 4; sVal |= Char2Bin(sSrc[i+0]);
sVal <<= 4; sVal |= Char2Bin(sSrc[i+1]);
sVal <<= 4; sVal |= Char2Bin(sSrc[i+2]);
sVal <<= 4; sVal |= Char2Bin(sSrc[i+3]);
TRACE(_T("%c%c%c%c=%04XH\n"), sSrc[i+0], sSrc[i+1], sSrc[i+2], sSrc[i+3], sVal);
}
}
//char型指针,指向的内容是“0123456789abcdef”的字符数组,我现在想要将其转换成USHORT型数据{0123,4567,89ab,........}.
#define MAXUS 512000
char s[]="0123456789abcdef";
unsigned short us[MAXUS];
int i,j;
inline unsigned short hex(char c) {
if ('0'<=c && c<='9') return (unsigned short)(c-'0');
if ('a'<=c && c<='f') return (unsigned short)(c-'a'+10);
if ('A'<=c && c<='F') return (unsigned short)(c-'A'+10);
return 0;
}
int main() {
i=0;
j=0;
while (1) {
if (s[j ]==0) break;
if (s[j+1]==0) break;
if (s[j+2]==0) break;
if (s[j+3]==0) break;
us[i]=hex(s[j ])<<12
|hex(s[j+1])<< 8
|hex(s[j+2])<< 4
|hex(s[j+3]);
i++;
if (i>=MAXUS) break;
j+=4;
}
j=i;
for (i=0;i<j;i++) printf("%04hx ",us[i]);
return 0;
}