将16进制(2个字符表达的)转成十进制整数
#include <stdio.h>
int tolower(int c)
{
if(c >= 'A' && c <= 'Z')
{
c = c + 'a' - 'A';
}
return c;
}
int htoi(char *s)
{
int i;
int n = 0;
if(s[0] == '0' && (s[1] == 'x' ||s[1] == 'X'))
{
i = 2;
}
else
{
i = 0;
}
for(;(s[i] >= '0' && s[i] <= '9')||(s[i] >= 'a'&& s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z');i++)
{
if(tolower(s[i]) >= 'a' && tolower(s[i]) <= 'z')
{
n = 16 * n + 10 + (tolower(s[i]) - 'a');
}
else
{
n = 16 * n + (tolower(s[i]) - '0');
}
}
return n;
}
int main()
{
char* s1 = "0x11";
char* s2 = "11";
int n1 = htoi(s1);
int n2 = htoi(s2);
printf("n1 = %d, n2 = %d\n",n1,n2);
return 0;
}#include <stdio.h>
int tolower(int c)
{
if(c >= 'A' && c <= 'Z')
{
c = c + 'a' - 'A';
}
return c;
}
int htoi(char *s)
{
int i;
int n = 0;
if(s[0] == '0' && (s[1] == 'x' ||s[1] == 'X'))
{
i = 2;
}
else
{
i = 0;
}
for(;(s[i] >= '0' && s[i] <= '9')||(s[i] >= 'a'&& s[i] <= 'z')||(s[i] >= 'A' && s[i] <= 'Z');i++)
{
if(tolower(s[i]) >= 'a' && tolower(s[i]) <= 'z')
{
n = 16 * n + 10 + (tolower(s[i]) - 'a');
}
else
{
n = 16 * n + (tolower(s[i]) - '0');
}
}
return n;
}
int main()
{
char* s1 = "0x11";
char* s2 = "11";
int n1 = htoi(s1);
int n2 = htoi(s2);
printf("n1 = %d, n2 = %d\n",n1,n2);
return 0;
}
写入文件格式
int fprintf(FILE *stream, const char *format, ...)
如:
fprintf(f,"%02x",ch1);
c语言中文网整理得不错
char* s1 = "0x11";
gdb调试:
(gdb) p *s1@7
$4 = "0x11\000\061\061"
(gdb) p/x *s1@7
$6 = {0x30, 0x78, 0x31, 0x31, 0x0, 0x31, 0x31}
(gdb) p *s1@7
$7 = "0x11\000\061\061"
(gdb) p *s1@5
$8 = "0x11"
43 char* s1 = "0x112";
(gdb) p *s1
$1 = 48 '0'
(gdb) p *s1[1]
Cannot access memory at address 0x78
(gdb) p s1[1]
$2 = 120 'x'
(gdb) p *s1@8
$3 = "0x112\000\061\061"
(gdb) p/x *s1@8
$4 = {0x30, 0x78, 0x31, 0x31, 0x32, 0x0, 0x31, 0x31}
一直没懂
\061
是啥? 解释: 八进制ASCII码值61,即十进制49,意思是字符’1’。
(gdb) p/o *s1@8
$5 = {060, 0170, 061, 061, 062, 0, 061, 061}
|