普通字符串和Hex字符串转换
写了个普通字符串和Hex字符串转换函数,权当练练手吧
#include <string.h>
//将普通字符串转化成Hex字符串
void str2hex(char* str, char* hex)
{
const char* cHex = "0123456789ABCDEF";
int i=0;
for(int j =0; j < strlen(str); j++)
{
unsigned int a = (unsigned int) str[j];
hex[i++] = cHex[(a & 0xf0) >> 4];
hex[i++] = cHex[(a & 0x0f)];
}
hex[i] = '\0';
}
//将Hex字符串转换成普通字符串
void hex2str(char* hex,char* str)
{
int i=0;
for(int j =0; j < strlen(hex) -1; )
{
unsigned int a = hex2int(hex[j++]);
unsigned int b = hex2int(hex[j++]);
str[i++] = char(a *16 + b);
}
str[i] = '\0';
}
//将Hex字符转换成无符号整型
unsigned int hex2int(char c)
{
if( c >= '0' && c <= '9')
{
return (unsigned int) (c -48);
}
else if( c >= 'A' && c <= 'B')
{
return (unsigned int) (c -65);
}
else if( c >= 'a' && c <= 'b')
{
return (unsigned int) (c - 97);
}
else
{
return 0;
}
}
//将普通字符串转化成Hex字符串
void str2hex(char* str, char* hex)
{
const char* cHex = "0123456789ABCDEF";
int i=0;
for(int j =0; j < strlen(str); j++)
{
unsigned int a = (unsigned int) str[j];
hex[i++] = cHex[(a & 0xf0) >> 4];
hex[i++] = cHex[(a & 0x0f)];
}
hex[i] = '\0';
}
//将Hex字符串转换成普通字符串
void hex2str(char* hex,char* str)
{
int i=0;
for(int j =0; j < strlen(hex) -1; )
{
unsigned int a = hex2int(hex[j++]);
unsigned int b = hex2int(hex[j++]);
str[i++] = char(a *16 + b);
}
str[i] = '\0';
}
//将Hex字符转换成无符号整型
unsigned int hex2int(char c)
{
if( c >= '0' && c <= '9')
{
return (unsigned int) (c -48);
}
else if( c >= 'A' && c <= 'B')
{
return (unsigned int) (c -65);
}
else if( c >= 'a' && c <= 'b')
{
return (unsigned int) (c - 97);
}
else
{
return 0;
}
}
posted on 2010-06-13 21:06 Hero King 阅读(4027) 评论(0) 编辑 收藏 举报