ios - 如何准确地将 NSData 转换为 struct

标签 ios nsdata bluetooth-lowenergy

关闭。这个问题需要details or clarity .它目前不接受答案。












想改进这个问题?通过 editing this post 添加详细信息并澄清问题.

6年前关闭。




Improve this question




我从设备(BLE)获得数据: <840100ec d5045715 00010014 00240018 00>

但是 第二个字节无法准确转换。像这些:

enter image description here

但我可以使用 Uint8 数组,为什么?谢谢你。
enter image description here

像这样的代码:

    // I got the data:<840100ec d5045715 00010014 00240018 00>

    case SPK_FEEDBACK_HistoryDataPort:
    // Log
    NSLog(@"receive data:%@", [NSData dataWithBytes:originalCommandBytes length:sizeof(D2MHistoryDataPort)]);

    // originalCommandBytes dataType:UInt8 *
    D2MHistoryDataPort *historyData = (D2MHistoryDataPort *)originalCommandBytes;

    // Log
    NSLog(@"收到硬件返回的0x%x指令(历史数据体): 历史数据包的索引:%d; 时间戳:%d; 步数:%d; 卡路里:%d; 距离:%d; 睡眠:%d; 运动时长:%d",
          historyData->cmd,
          historyData->index,
          (unsigned int)historyData->timeStamp,
          historyData->steps,
          historyData->calories,
          historyData->distance,
          historyData->sleep,
          historyData->duration);
    break;

    // I declare this struct in another class
    typedef struct {
        UInt8 cmd;
        UInt16 index;
        UInt32 timeStamp;
        UInt16 steps;// 步数
        UInt16 calories;// 卡路里
        UInt16 distance;// 距离,单位m
        UInt16 sleep;// 睡眠
        UInt16 duration;// 运动时长,单位minute
     } D2MHistoryDataPort;

最佳答案

编译器如何在内存中布置结构的各个字段取决于实现。通常编译器必须添加填充以正确对齐字段,它甚至可能重新排序它们(通过对相同大小的字段进行分组)以减少所需的填充和结构的整体大小。

您可以使用 __attribute__((packed)) 关闭此行为。 :

typedef struct __attribute__((packed)) {
    UInt8 cmd;
    UInt16 index;
    UInt32 timeStamp;
    UInt16 steps;// 步数
    UInt16 calories;// 卡路里
    UInt16 distance;// 距离,单位m
    UInt16 sleep;// 睡眠
    UInt16 duration;// 运动时长,单位minute
 } D2MHistoryDataPort;

关于ios - 如何准确地将 NSData 转换为 struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36490630/

相关文章:

bluetooth - 使用 BLE 芯片将设备连接到智能手机

安卓 4.3 蓝牙

ios - NSManagedObjectContext:带有通知中心的 performBlockAndWait 与 performBlock

ios - 如何在 JavaScriptCore 中包含外部库?

cocoa - 如何将 WebView 中的图像数据获取到 NSData 对象中?

objective-c - NSFileHandle -readDataOfLength : return autoreleased NSData? 是否

ios - cocoa iOS/触摸 : Keeping a subview of the UITableViewCell contentView right-aligned

ios - 带有自定义 MKAnnotation 的 MKMapView

cocoa RTF : NSData vs. NSAttributedString?

ios - 如何修复此错误 "Could not find module ' CzsBleSdk' for architecture 'x86_64' ;发现 : arm64, ARM “