结构体和NSData转换

2017-10-18  本文已影响0人  iOS扫地僧

定义结构体(结构体定义的时候注意32和64位系统的不同)

数据类型 和 结构体的 sizeof() -- 32和64位系统

struct   MEDIAHEAD
{
    int  start;
    int  mediaType;
    long long  dataLength;
    long long  time;
    int  headLength;
    int  end;
};

结构体初始化并转换NSData

NSDate* dat1 = [NSDate dateWithTimeIntervalSinceNow:0];
NSTimeInterval time=[dat1 timeIntervalSince1970]*1000;
struct MEDIAHEAD mediaHead={100,1,10000,time,40,100};
NSData * msgData = [[NSData alloc]initWithBytes:&mediaHead length:sizeof(mediaHead)];
NSLog(@"结构体data:msgData = %@",msgData);

输出

结构体data:msgData = <64000000 01000000 10270000 00000000 ac4a812d 5f010000 28000000 64000000>

NSData转换为结构体

struct  MEDIAHEAD  infoStruct2;
[msgData getBytes:&infoStruct2 length:sizeof(infoStruct2)];
NSLog(@"\ninfoStruct2.start = %d \ninfoStruct2.mediaType = %d \ninfoStruct2.dataLength = %zi \ninfoStruct2.time = %zi \ninfoStruct2.headLength = %d \ninfoStruct2.end = %d",infoStruct2.start,infoStruct2.mediaType,infoStruct2.dataLength,infoStruct2.time,infoStruct2.headLength,infoStruct2.end);

输出

infoStruct2.start = 100 
infoStruct2.mediaType = 1 
infoStruct2.dataLength = 10000 
infoStruct2.time = 1508296968876 
infoStruct2.headLength = 40 
infoStruct2.end = 100
上一篇 下一篇

猜你喜欢

热点阅读