C语言-十进制十六进制转换

阳光穿透心脏的1/2处 2022-03-08 10:24 418阅读 0赞

目录

    • 1.Rain_Conversion
    • 2.Gali_Conversion

   一个朋友提到十进制数转十六进制后以字符串输出,基于此写了两段代码以供参考,其中涉及数组成员反转,指针等特别基础的用法。仅娱乐。


1.Rain_Conversion

  1. #include "stdio.h"
  2. #include "string.h"
  3. #include "stdlib.h"
  4. #include "limits.h"
  5. #define MAX_SIZE 100
  6. int Conversion(long n,char *ret)
  7. {
  8. int remainder = 0;
  9. char hex[16] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
  10. int result[MAX_SIZE];
  11. int i = 0;
  12. char *rets =NULL;
  13. memset(result,0x0,MAX_SIZE);
  14. if(n==0){
  15. *ret = '0';
  16. return 0;
  17. }
  18. while(n>0){
  19. remainder = n%16;
  20. result[i++] = remainder;
  21. n /= 16;
  22. }
  23. rets = ret;
  24. for(i=i-1;i>=0;i--){
  25. *ret = hex[result[i]];
  26. ret++;
  27. }
  28. //*ret = '\0';
  29. ret = rets;
  30. return 0;
  31. }
  32. int main()
  33. {
  34. long a = 0;
  35. char *ret = NULL;
  36. ret = (char *)malloc(MAX_SIZE);
  37. REPEAT:
  38. printf("please input num %ld - %ld\n",LONG_MIN,LONG_MAX);
  39. if( (scanf("%ld",&a) != 1)||(a<0) ){
  40. puts("input err");
  41. goto REPEAT;
  42. }
  43. if( !Conversion(a,ret) ){
  44. printf("num a = %ld,ret = 0x%s\n",a,ret);
  45. }
  46. free(ret);
  47. }

2.Gali_Conversion

-—————— 代码出自咖喱鸡

  1. #include "stdio.h"
  2. int main(void)
  3. {
  4. int j,re;
  5. long int n;
  6. int i = 0;
  7. char str[100],ch;
  8. puts("pleas input n(long int)");
  9. scanf("%ld",&n);
  10. while(n!=0){
  11. re = n%16;
  12. if( re>9 ){
  13. str[i++] = (char)(re - 10) + 'a';
  14. }else{
  15. str[i++] = (char)re + '0';
  16. }
  17. n = n>>4;
  18. }
  19. str[i--] = '\0';
  20. for(j=0;j<((i+1)>>1);j++){
  21. ch = str[i-j];
  22. str[i-j] = str[j];
  23. str[j] = ch;
  24. }
  25. printf(" 0x%s\n",str);
  26. }

发表评论

表情:
评论列表 (有 0 条评论,418人围观)

还没有评论,来说两句吧...

相关阅读