1.前言
经常在编程时会遇到打印Data Buffer的情况,下面定义了DUMP8、DUMP16、DUMP32,很方便来打印Data Buffer里面的数据。
2.hal_print.c
#include "hal_print.h"
int hal_print_dump(const char *fmt, unsigned int size, unsigned int count, const void *buffer)
{
char buf[255];
unsigned int len=0,i=0;
switch( size )
{
case sizeof(uint32_t):
while(i<count && len<sizeof(buf))
{
len += HAL_SNPRINTF(&buf[len], sizeof(buf) - len, fmt, *(uint32_t *)((uint32_t *)buffer+i));
i++;
}
break;
case sizeof(uint16_t):
while(i<count && len<sizeof(buf))
{
len += HAL_SNPRINTF(&buf[len], sizeof(buf) - len, fmt, *(uint16_t *)((uint16_t *)buffer+i));
i++;
}
break;
case sizeof(uint8_t):
default:
while(i<count && len<sizeof(buf))
{
len += HAL_SNPRINTF(&buf[len], sizeof(buf) - len, fmt, *(uint8_t *)((uint8_t *)buffer+i));
i++;
}
break;
}
if (len + 1 < sizeof(buf)) {
buf[len++] = '\r';
}
if (len + 1 < sizeof(buf)) {
buf[len++] = '\n';
}
if (len + 1 < sizeof(buf)) {
buf[len++] = '\0';
}
HAL_PRINT("%s",buf);
return len;
}
3.hal_print.h
#ifndef __HAL_PRINT_H__
#define __HAL_PRINT_H__
#include "stdio.h"
#include "stdint.h"
#define HAL_SNPRINTF snprintf
#define HAL_PRINT printf
int hal_print_dump(const char *fmt, unsigned int size, unsigned int count, const void *buffer);
#define DUMP8(str, buf, cnt) hal_print_dump(str, sizeof(uint8_t), cnt, buf)
#define DUMP16(str, buf, cnt) hal_print_dump(str, sizeof(uint16_t), cnt, buf)
#define DUMP32(str, buf, cnt) hal_print_dump(str, sizeof(uint32_t), cnt, buf)
#endif // __HAL_PRINT_H__
4.main.c
#include "stdio.h"
#include "stdint.h"
#include "hal_print.h"
uint8_t dataBuf[52];
int main(void)
{
uint8_t i;
// init data
for(i = 0; i < sizeof(dataBuf); i++)
{
dataBuf[i] = i + 1;
}
// print data
printf("DUMP8:\r\n");
DUMP8("0x%02x ", dataBuf, 30);
printf("\r\nDUMP16:\r\n");
DUMP16("0x%04x ", dataBuf, 20);
printf("\r\nDUMP32:\r\n");
DUMP32("0x%08x ", dataBuf, 10);
return 0;
}
5.测试效果
6.资料下载
完整的代码下载地址如下:
https://download.csdn.net/download/ZHONGCAI0901/15482516