微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

任何基数到十进制的转换

如何解决任何基数到十进制的转换

我一直在撞墙,直到被驱使我写了我的第一个StackOverflow帖子,我试图将代表任意基数的字符串转换为基数10。

int* basetoDec(int base,char* value){
  //after three hours its time for a full restart :( give it up for hour 4!!!                            
  printf("%s has a length of %d\n",value,(int)strlen(value));
  int* res = (int*)malloc(1 * sizeof(int));                                           
  int p = 1;
  for(int i = strlen(value)-1; i >= 0; --i){ // moving backwards through the list                        
    int digit; // there is something I dont understand going on with the 0                               
    printf("value at i:%d %c\n",i,value[i]);
    if(value[i] >= 48 && value[i] <= 57){
      digit = value[i] - 48;


    }
    if(value[i] >= 65 && value[i] <= 90){
      digit = value[i] - 55;
    }
    printf("%d * %d\n",digit,p);

    *res += digit * p;
    p = p * base;
  }
  return res;

从我可以看出的问题是,当我运行代码时,字符串不是我期望的长度(与结束字符有关),因为我得到了很多垃圾数字,这些数字使数字看起来比它是。 欢迎所有反馈 我希望我做对了

以33(八进制为41)运行时,我会得到这些结果


41 has a length of 4
value at i:3 
0 * 1 //notice this 0 and the following one,where did they come from???
value at i:2 1
1 * 8
value at i:1 
1 * 64
value at i:0 4
4 * 512
2120

解决方法

使用res指向的缓冲区无需初始化。 通过malloc()分配的缓冲区的初始值是不确定的,使用不确定的值将调用未定义的行为

您应该添加初始化并检查分配是否成功,如下所示:

  int* res = (int*)malloc(1 * sizeof(int));
  if (res == NULL) return NULL; /* check */
  *res = 0; /* initialization */

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。