极客工坊

 找回密码
 注册

QQ登录

只需一步,快速开始

查看: 8731|回复: 1

贡献一个开源的整型数转字符串函数

[复制链接]
发表于 2012-9-22 16:54:18 | 显示全部楼层 |阅读模式
本帖最后由 弘毅 于 2017-11-3 12:24 编辑
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

  4. uint_fast8_t integer_number_to_string (int32_t input_number, char leader_character, uint_fast8_t display_width, char numeric_string[], uint_fast8_t array_len)  //input_number range is INT32_MAX to INT32_MIN. Returns the numeric string length.
  5. {
  6.   const uint_fast8_t INTERMEDIATE_MAX_WIDTH = 1 + 10;  //sign + Max significant figures, Max significant figures = int32_t floor(log10(-INT32_MIN)) + 1
  7.   
  8.   char intermediate_string[INTERMEDIATE_MAX_WIDTH + 1];
  9.   
  10.   if (leader_character < '\x0')
  11.   {
  12.     return 0;
  13.   }
  14.   if (display_width >= array_len)
  15.   {
  16.     return 0;
  17.   }
  18.   if (array_len <= 1)
  19.   {
  20.     return 0;
  21.   }
  22.   
  23.   #if defined(__cplusplus)
  24.   int_fast8_t intermediate_len = sprintf(intermediate_string, "%-""li", input_number);
  25.   #else
  26.   int_fast8_t intermediate_len = sprintf(intermediate_string, "%-"PRIi32, input_number);
  27.   #endif
  28.   if (intermediate_len > display_width)
  29.   {
  30.     return 0;
  31.   }

  32.   int_fast8_t i = 0;
  33.   int_fast8_t n = display_width - (intermediate_len + 1);
  34.   if (isgraph(leader_character))
  35.   {
  36.     while (i <= n)
  37.     {
  38.       numeric_string[i] = leader_character;
  39.       ++i;
  40.     }
  41.   }
  42.   n = i + intermediate_len;
  43.   int_fast8_t j = 0;
  44.   while (i <= n)
  45.   {
  46.     numeric_string[i] = intermediate_string[j];
  47.     ++i;
  48.     ++j;
  49.   }
  50.   i -= 1;
  51.   return i;  //Returns the numeric string length
  52. }
复制代码


==========================
纯C11草案标准写的,并兼容Arduino
有什么使用问题欢迎留言
回复

使用道具 举报

 楼主| 发表于 2012-10-13 02:46:54 | 显示全部楼层
为更方便大家应用,变更了开源许可证
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则 需要先绑定手机号

Archiver|联系我们|极客工坊

GMT+8, 2024-4-28 05:15 , Processed in 0.038885 second(s), 17 queries .

Powered by Discuz! X3.4 Licensed

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表