嵌入式基础-数据的趣味学堂
QQ群-名称:嵌入式交流 ;群号:933192343;微信号:WangMing_GZ
1.数据不同的显示方式
C语言同样的数据可以通过不用的方式进行展示
#include <unistd.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
int i = 0;
int len = 0;
unsigned char buf_str[24] = "Hello World";
unsigned char buf_dec[24] = {72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100};
unsigned char buf_hex[24] = {0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64};
len = strlen((char *)buf_str);
printf("dec: ");
for(i = 0;i < len;i++)
{
printf("%d ",buf_str[i]);
}
printf("\n");
printf("hex: ");
for(i = 0;i < len;i++)
{
printf("0x%02x ",buf_str[i]);
}
printf("\n");
printf("buf_dec: %s\n",buf_dec);
printf("buf_hex: %s\n",buf_hex);
return 0;
}
运行程序之后的打印结果
2.数据的实践使用
在日常编程过程中,对于RAW和字符串共存的数据,不能使用 strlen 函数去判断数据的长度,要根据定义好的长度去做解析
int main(void)
{
int len = 0;
unsigned char buf_str[24];
unsigned char buf_hex[24] = {0x55, 0xaa, 0x00, 0x03, 0x0b, 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64};
memset(buf_str,0,sizeof(buf_str));
len = strlen((char *)buf_hex);
printf("buf_hex len: %d\n",len);
memcpy(buf_str,buf_hex + 5,0x0b);
printf("buf_str: %s\n",buf_str);
return 0;
}
strlen 的长度只有2,因为有个RAW的0x00,所以对于RAW和字符串共存的数据只能按照定义去解析