|
vc代码
注意:在linux下是没有 ltoa这个函数,因此在linux下可用这样来实现:
用sprintf格式化字符串,%x(16进制),%o(8进制),%u(无符号十进制); 字符串转数字可用strtol来实现,这个函数第三个形参 代表采用的进制方式,如base值为10则采用10进制;
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #include <locale.h> 5 int main() { 6 int i,v; 7 char bs[33]; 8 char b[33]; 9 char hs[9]; 10 char h[9]; 11 char s[4]; 12 char *e; 13 14 // 十进制整数转二进制串; 15 i=1024; 16 ltoa(i,b,2); 17 sprintf(bs,"%032s",b); 18 printf("i=%d,bs=%s\n",i,bs); 19 // 十进制整数转十六进制串; 20 i=1024; 21 ltoa(i,h,16); 22 sprintf(hs,"%08s",h); 23 printf("i=%d,hs=%s\n",i,hs); 24 // 十六进制字符串转成十进制数 25 strcpy(hs,"00000400"); 26 sscanf(hs,"%x",&i); 27 printf("hs=%s,i=%d\n",hs,i); 28 // 二进制字符串转化为十六进制字符串; 29 strcpy(bs,"00000000000000000000010000000000"); 30 i=strtol(bs,&e,2); 31 ltoa(i,h,16); 32 sprintf(hs,"%08s",h); 33 printf("bs=%s,hs=%s\n",bs,hs); 34 // 二进制字符串转化为十进制数; 35 strcpy(bs,"00000000000000000000010000000000"); 36 i=strtol(bs,&e,2); 37 printf("bs=%s,i=%d\n",bs,i); 38 // 十六进制字符串转成二进制串 39 strcpy(hs,"00000400"); 40 sscanf(hs,"%x",&i); 41 ltoa(i,b,2); 42 sprintf(bs,"%032s",b); 43 printf("hs=%s,bs=%s\n",hs,bs); 44 // ASC\GBK字符串转十六进制串 45 strcpy(s,"a汉"); 46 i=0; 47 while (1) { 48 if (0==s[i]) break; 49 sprintf(hs+i*2,"%02X",(unsigned char)s[i]); 50 i++; 51 } 52 setlocale(LC_ALL,"chs"); 53 printf("s=%s,hs=%s\n",s,hs); 54 // 十六进制字符串转成汉字(GBK)及字符(ASC) 55 strcpy(hs,"61BABA"); 56 i=0; 57 while (1) { 58 if (1!=sscanf(hs+i*2,"%2x",&v)) break; 59 s[i]=(char)v; 60 i++; 61 } 62 s[i]=0; 63 printf("hs=%s,s=%s\n",hs,s); 64 65 return 0; 66 67
|