简易printf打印实现,占用内存非常小------<嵌入式开发自学笔记>
2017-11-15 15:17
330 查看
//打印单个字符 void print_ch(const char ch) { //这里实现你的串口发送单个字符的函数 // LPUART_WriteBlocking(LPUART0, (uint8_t *)&ch, 1); } //打印整数,不明白的可以网上查查,怎么回事,print_int()又调用了print_int() void print_int(int dec) { if(dec < 0) { print_ch('-'); dec = -dec; } if(dec / 10) print_int(dec / 10); print_ch(dec%10 + '0'); } //转换成十六进制 static void get_hex(uint8_t hex) { const uint8_t ascii_zero = 48; const uint8_t ascii_a = 65; if ((hex >= 0) && (hex <= 9)) { print_ch(hex + ascii_zero); } if ((hex >= 10) && (hex <= 15)) { print_ch(hex - 10 + ascii_a); } } //以十六进制格式输出 void print_hex(uint32_t hex) { if(hex / 16) print_hex(hex/16); get_hex(hex%16); } //打印字符串 void print_str(const char *ptr) { while(*ptr) { print_ch(*ptr); ptr++; } } //打印浮点 void print_float(const float flt) { int tmpint = (int)flt; int tmpflt = (int)(100000 * (flt - tmpint)); if(tmpflt % 10 >= 5) { tmpflt = tmpflt / 10 + 1; } else { tmpflt = tmpflt / 10; } print_int(tmpint); print_ch('.'); print_int(tmpflt); } //带格式打印, void my_printf(const char *format,...) { va_list ap; va_start(ap,format); while(*format) { if(*format != '%') { print_ch(*format); format++; } else { format++; switch(*format) { case 'c': { char valch = va_arg(ap,int); print_ch(valch); format++; break; } case 'd': { int valint = va_arg(ap,int); print_int(valint); format++; break; } case 's': { char *valstr = va_arg(ap,char *); print_str(valstr); format++; break; } case 'f': { float valflt = va_arg(ap,double); print_float(valflt); format++; break; } case 'x': case 'X': { int valhex = va_arg(ap,int); if(((uint32_t)valhex)<16) { print_ch('0'); } print_hex((uint32_t)valhex); format++; break; } default: { print_ch(*format); format++; } } } } va_end(ap); }
相关文章推荐
- cocos2dx 3.x 自学笔记 <三> cocos2dx 2.x 3.x 内存管理机制
- <Android入门笔记>第一章 搭建Android开发环境
- 实战解决问题开发出功能固然重要--->基本功锤炼和技术的实现原理,也非常重要
- iOS学习笔记11—代码里打印程序所占用的内存
- 黑马程序员自学笔记 Java基础<五>---> 多线程
- 嵌入式开发之C基础学习笔记06--数组和指针(非常重要,难点)
- Effective C# 学习笔记(三十一)利用IComparable<T>和IComparer<T>接口来实现排序关系
- IOS开发笔记:编译时出现的错误<1>
- html5之<video>开发实现音乐播放控…
- Unity3D笔记 愤怒的小鸟<二> 实现Play界面
- java笔记--用ThreadLocal管理线程,Callable<V>接口实现有返回值的线程
- 服务器开发之内存<二>: 带生命周期的小内存块
- 想实现自己的地理应用程序?建议参考<<使用Rails和Ajax开发Google地图应用程序>>
- iOS 开发笔记 <我的坐标demo>
- Unity3D笔记 愤怒的小鸟<四> 实现Selelction界面
- <javascript学习笔记>javascript 实现隔行变色
- <Android开发代码库>achartengine实现柱状图、圆饼图、线图等
- 学习java笔记 --- 一个实现Iterable<E>接口的小范例
- cocos2d-x 3.0开发笔记---Vector<T>深入学习
- [转贴] u-boot 分析 - <节选> [嵌入式Linux系统开发技术详解-基于ARM]