奇怪的 指针转换,求解

--超 2018-11-14 05:50:54

1. 转换成功
static void get_data( char* pData, float* pfData )
{
int i ;
for( i = 0; i < 10; i++ )
{
pfData[i] = ((float)((int16_t)( *( (int16_t*)(&pData[2*i]) ) ))) * 0.003 ;
}
}
取char 地址,后转换成int16_t* 指针, 将pData[0] pData[1] 当成int16_t取出

2. 失败

typedef struct {
uint8_t low ;
uint8_t hig ;
} short_t;
short_t data[FRM_DATAS] ;
printf("%d \n", (*(int16_t*)((int8_t*)((char*)&(pData->data[i])))) );

使用pData->data[i].low 也失败
使用 .hig 成功, 但是只能取出一个字节数据,不像【1】中,取的是双字节

???
请教各位大佬解答
...全文
37 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
--超 2018-11-20
  • 打赏
  • 举报
回复
1. 编译没问题,就是运行出错。
2. short_t 这个结构体,就是用于强制字节序的。

3. 单独gcc 跑了一下,一点问题没有,也不存在越界
#include <stdio.h>
2 #include <stdint.h>
3
4 typedef struct {
5 int8_t low ;
6 int8_t hig ;
7 }short_t ;
8
9 void main()
10 {
11 short_t data[10] ;
12 data[0].low = 1 ;
13 data[0].hig = 2 ;
14 data[1].low = 3 ;
15 data[1].hig = 4 ;
16
17 int i ;
18 for( i = 2; i < 10; i++ )
19 {
20 data[i] = *(short_t*)&i ;
21 }
22
23 for(i = 0 ; i < 10 ; i++ )
24 {
25 printf("%x \n", (*(int16_t*)((int8_t*)((char*)&(data[i])))) );
26 }
27 }

输出:
201
403
2
3
4
5
6
7
8
9

总结: 一点问题没有,也许嵌入式端编译器的锅??


领域灬alone 2018-11-16
  • 打赏
  • 举报
回复
注意下类型长度以及偏移
英雄@末路 2018-11-15
  • 打赏
  • 举报
回复
这个参考下前面的一个帖子,指针和数组在取地址符时候结果并不一样
xiaohuh421 2018-11-15
  • 打赏
  • 举报
回复
前面说的方法, 都有一个前提. 字节序相同哈. 字节序不同, 是不能这样直接拿的.
xiaohuh421 2018-11-15
  • 打赏
  • 举报
回复
取个值需要这么复杂吗? char buf[0x100]; short val = *(short*)&buf[4]; //可以直接把第5个字节起的2个字节,解析成一个short类型. 其它类型, 都可以参考这样来取值. int val = *(int*)&buf[4]; doubble val = *(doubble *)&buf[4]; .......
冷风1023 2018-11-15
  • 打赏
  • 举报
回复
求解为什么会这样
northwesternwind 2018-11-14
  • 打赏
  • 举报
回复
你把类型定义里面的low和high位置交换一下试试。

69,382

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧