本文参考Hacker's Delight By Henry S. Warren,使用所谓的“魔数”计算,让你领略所谓的“奇技淫巧”。
详细的程序
/* * FileName : format2str.c * Author : xiahouzuoxin @163.com * Version : v1.0 * Date : 2014/4/8 11:08:40 * Brief : * * Copyright (C) MICL,USTB */#include "format2str.h" /* * @brief * == Use Example * str = (char *)malloc(k*sizeof(char)); * if (str) { * int32_to_str(x, str, n); // n <= k * } * == Be careful of choose the input n * @inputs * x - Interger numbers * n - * x>0, n >= bit of x in decimal format + 1 * x<0, n >= bit of x in decimal format + 2 * @outputs * str - Converted string * @retval * If success return 0, else others. */int32_tint32_to_str(int32_tx,char*str,uint32_tn){uint32_tremain=0;uint32_tdiv_x=0;uint32_tle_zero=0;if(x<0){x=-x;le_zero=1;}str[--n]='\0';while((x>0)&&(n>0)){div_x=DIV10(x);remain=x-((div_x<<3)+(div_x<<1));// x - div_x * 10x=div_x;str[--n]=remain+'0';}while(n>1){str[--n]='0';}if(le_zero>0){str[--n]='-';}else{str[--n]='0';}return(n);}
/* * FileName : format2str.h * Author : xiahouzuoxin @163.com * Version : v1.0 * Date : 2014/4/9 10:15:09 * Brief : * * Copyright (C) MICL,USTB */#ifndef _FORMAT2STR_H#define _FORMAT2STR_H#ifdef __cplusplusextern"C"{#endif#include <stdint.h>/* * Magic Number 0x66666667 * Refrence to <<Hacker's Delight>> By Henry S. Warren */#define DIV5(x) (((int64_t)x*0x66666667L) >> 33)#define DIV10(x) (((int64_t)x*0x66666667L) >> 34)externint32_tint32_to_str(int32_tx,char*str,uint32_tn);#ifdef __cplusplus}#endif#endif