分析字符型变量的ascii值的由来 利用sscanf和sprintf实现ASCII和16进制互转
/*利用sscanf和sprintf实现 ASCII和16进制互转,今天小编就来说说关于分析字符型变量的ascii值的由来 利用sscanf和sprintf实现ASCII和16进制互转?下面更多详细答案一起来看看吧!
分析字符型变量的ascii值的由来 利用sscanf和sprintf实现ASCII和16进制互转
/*
利用sscanf和sprintf实现 ASCII和16进制互转
"314D63"==>{0x31,0x4d,0x63},
{0x31,0x4d,0x63}==>"314D63"
*/
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
char* AsciiStrTohexStr( unsigned char* din, int din_len, char *dout, int *dout_len )
{
int i;
int c = 0;
int j = 0;
for ( i = 0; i < din_len; i )
{
char tmp[20] = { 0 };
sprintf( tmp, "X", din[i] );
strcat( dout, tmp );
j = 2;
}
dout[j] = '\0';
*dout_len = j;
return(dout);
}
unsigned char* hexStrToAsciiStr( unsigned char* din, int din_len, unsigned char *dout, int *dout_len )
{
int i;
int c = 0;
int j = 0;
for ( i = 0; i < din_len; i = 2 )
{
sscanf( (const char *) din i, "X", &c );
dout[i / 2] = (unsigned char) (c & 0xFF);
j ;
}
*dout_len = j;
return(dout);
}
int main()
{
//利用sscanf ASCII转16进制 "314D63"==>{0x31,0x4d,0x63}
unsigned char din[512] = "314D63";
unsigned char dout[512] = { 0 };
int din_len = strlen( din );
int dout_len = 0;
hexStrToAsciiStr( din, din_len, dout, &dout_len );
printf( "dout1 hex: " );
for ( int i = 0; i < dout_len; i )
{
printf( "x ", dout[i] );
}
printf( ", dout1 str:%s\n", dout );
//利用sprintf实现16进制{0x31,0x4d,0x63}==>"314D63"
unsigned char din2[512] = { 0x31, 0x4D, 0x63 };
unsigned char dout2[512] = { 0 };
int din2_len = 3;
int dout2_len = 0;
AsciiStrTohexStr( din2, din2_len, dout2, &dout2_len );
printf( "dout2 hex: " );
for ( int i = 0; i < dout2_len; i )
{
printf( "x ", dout2[i] );
}
printf( ", dout2 str:%s\n", dout2 );
return(0);
}
/*
dout1 hex: 31 4d 63 , dout1 str:1Mc
dout2 hex: 33 31 34 44 36 33 , dout2 str:314D63
*/
,免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com