用于将以10为基数的数字转换为以“b”为基数的数字的函数encode不打印任何内容

js81xvg6  于 2023-02-03  发布在  其他
关注(0)|答案(1)|浏览(90)

我创建了这个函数来转换一个数字'd'在基地10到数字x在基地'b',不幸的是,该函数不打印,有人能帮助我吗?

// I don't understand why it doesn't print me the encode 

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 20
// the function created to convert a number 'd' in base 10 to a number in base 'b'
char *encode(unsigned int d, unsigned char b){
    if(b<2||b>16) return NULL;
    char * resto = calloc (SIZE, sizeof(char));
    int i=1;
    while(d>0){//rimanenza d%b 
        char rimanenza = d%b ;
        d = d/b;
        if (b>10 && b<=16){//if the base is between 10 and 16 'rimanenza' can't be a number
            if (rimanenza == 10) rimanenza = 'A';
            if (rimanenza == 11) rimanenza = 'B';
            if (rimanenza == 12) rimanenza = 'C';
            if (rimanenza == 13) rimanenza = 'D';
            if (rimanenza == 14) rimanenza = 'E';
            if (rimanenza == 15) rimanenza = 'F';
        }// save into resto from the end 
        resto [SIZE - i] = rimanenza;
        i++;
    }

    return resto  ;
    
}

int main (){
    unsigned int d = 126;
    unsigned char b = 3;    
    char *encoded = encode (d,b);
    printf ("%u in base %u = %s\n",d,b,encoded);
    free(encoded);
}
blmhpbnm

blmhpbnm1#

至少这些问题:

    • rimanenza < 10时,数字未转换为正确字符**

rimanenza在[0'...'9]范围内时,将其转换为字符['0 '...' 9']。

rimanenza += '0';
    • d最初为0时,while(d>0){无法形成"0"。**
    • 返回错误的偏移量**

return resto ;无法返回resto[]填充部分的开头。
更像是:

// return resto  ;
return memmove(resto, &resto[SIZE - i - 1], SIZE - i);
    • 如果calloc()失败,则无法测试**
    • 尺寸太小**

#define SIZE 20不足以满足encode(UINT_MAX, 2)的要求。@M欧姆

    • 缺少尾随 * 空字符***

代码需要在所有字符后加上'\0',才能成为 * string *。

    • 代码分配的大小不适合数据**

考虑只分配所需的资源。
未经测试的维修

#include <limits.h>
#define ENCODE_SZ (sizeof (unsigned) * CHAR_BIT + 1)  // Size buffer to base 2 worst case

char* encode(unsigned d, unsigned b) {
  if (b < 2 || b > 16) {
    return NULL;
  }
  char buffer[ENCODE_SZ];
  char *p = &buffer[ENCODE_SZ - 1]; // Point to last array element.
  *p = '\0'; // Terminate array with a null character.

  // Use a do loop to make sure code assigns at least 1 character.
  do {
    unsigned digit = d % b;
    // Look-up character;
    char ch = "0123456789ABCDEF"[digit];
    p--;
    *p = ch;
    d /= b;
  } while (d > 0);

  // Determine string length
  unsigned length = &buffer[ENCODE_SZ - 1] - p;
  unsigned size = length + 1;
  char *resto = malloc(size);
  if (resto == NULL) {
    return NULL;
  }

  // Copy and return.
  return strcpy(resto, p);
}

相关问题