面对挑战写我自己的my_itoa和我的atoi,它应该在C中将整数更改为ascii,反之亦然


誓言
2025-02-07 01:00:29 (24天前)


我错过了发帖,你总是教我很多!

所以,我有一个编写我自己的2个函数的任务,从整数变为ASCII,从嵌入式系统的ASCII变回整数,它们……

2 条回复
  1. 0# 那年 | 2019-08-31 10-32




    什么?
    </强>




    1. str = (uint8_t) malloc(len sizeof(uint8_t));
      while (*str != \0’)

    2. </code>


    这个

    my_atoi()

    代码没什么意义。代码分配内存未知的内存 - 然后立即尝试测试它们?



    然后不需要内存分配

    strlen()

    不需要。




    字符到十进制值
    </强>



    “我理解这部分会删除空字符:

    a = str -‘0’;

    “ - &gt;不完全。何时
    str

    是一个数字字符,

    str -‘0’

    将字符编码值(通常为ASCII)转换为其数值(如0到9)。



    str -‘0’

    不足以像十六进制数字

    ‘a’

    ,和

    ‘F’





    替代
    </强>



    相反,迭代

    ptr

    并计算一个运行总和。



    以下不符合2个编码目标,我将其留给OP作为子问题来处理。



    **不应使用字符串函数或库。

    **函数需要处理签名数据。






    1.   #include <ctype.h>
    2. // Convert 1 digit
      static int value(int ch) {
      if (isdigit(ch)) {
      return ch - 0’;
      }
      if (isxdigit(ch)) {
      ch = tolower(ch);
      const char *xdigits = abcdef”;
      return strchr(xdigits, ch) - xdigits + 10;
      }
      return INT_MAX; // non-digit
      }

    3. int32_t my_atoi(uint8_t ptr, uint8_t digits, uint32_t base) {
      int32_t sum = 0;
      while (
      ptr) {
      sum = base;
      sum += value(
      ptr++);
      }
      return sum;
      }

    4. </code>


    更好的代码将检测非数字输入,溢出,无转换等。未显示的其他注意事项包括处理a

    ‘-‘

    签名,验证范围内的基数。




    1. int32_t my_atoi(uint8_t ptr, uint8_t digits, uint32_t base) {
      int32_t sum = 0;
      while (isspace(
      ptr)) ptr++; // skip leading white space
      if (*ptr == ‘+’) ptr++; // Allow optional leading +
      bool digit_found = false;

    2. while (ptr) {
      unsigned digit = value(
      ptr++);
      if (digit >= base) {
      return INT_MIN; // TBD signal unexpected digit
      }
      if (sum >= INT_MAX/base && (sum > INT_MAX/base || digit > INT_MAX%base)) {
      // Overflow
      return INT_MIN; // TBD signal OF
      }
      sum *= base;
      sum += digit;
      digit_found = true;
      }

    3. if (*str) {
      sum = INT_MIN; // TBD signal unexpected junk at the end
      }
      if (!digit_found) {
      sum = INT_MIN; // TBD signal no digits
      }
      return sum;
      }

    4. </code>




    my_itoa()

    </强>



    寻求帮助

    my_itoa()

    ,审查

    实现良好的 itoa() 功能的正确方法是什么?

    。它确实有一个很好的答案

    1. -
    2. </A>
    3. 某处。


登录 后才能参与评论