我如何将这些数据从Little Endian转换为Big Endian

时间:2016-01-25 03:00:55

标签: objective-c endianness

我正在研究以小端输出数据的解决方案,我需要将其转换为objective-c,这是解决此问题的最佳方式。

从概念上讲,我理解发生了什么,我正在努力解决这个问题。

数据以CBC特征输出。

更新:

- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
    if (error) {
        NSLog(@"Error changing notification state: %@", [error localizedDescription]);
    } else {

        // Extract the data from the characteristic's value property
        // and display the value based on the characteristic type
        NSData *dataBytes = characteristic.value;
        if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:LOCK_OCCUPANCY_CHAR]]) {
            NSLog(@"%@",dataBytes);
        }
    }
}

这是日志的输出: 日志:< 79660000 7a660000 27671b80 0700>

从左到右,值表示为:开始时间,结束时间,Mac地址

时间戳是在unix时代。

1 个答案:

答案 0 :(得分:2)

基于上面的示例,您似乎正在从某个设备读取一些数据 - 并且数据正在打包在单个NSData缓冲区中。由于它是一种已知的格式 - 具有已知的大小,您可以将其读入结构中,以便您可以访问每个字段,并在需要时进行处理。

char rawData[] = {0x79, 0x66, 0x00, 0x00, 0x7a, 0x66, 0x00, 0x00, 0x27, 0x67, 0x1b, 0x80,0x07, 0x00};
NSData *sampleData = [NSData dataWithBytes:rawData length:sizeof(rawData)];

typedef struct MyStruct {
    uint32_t starttime;
    uint32_t endtime;
    uint8_t macaddress[6];
} MyStruct;

// first step - break the buffer into a structure

MyStruct sample;
[sampleData getBytes:&sample length:sizeof(sample)];

// second step - IF needed you need to process each member of the structure

// CFSwapInt32BigToHost is documented to take a known Big Endian (Network Order) to the format
// that the current CPU supports.   I'm not 100% sure that your sample data has reasonable timestamps
// so I can't verify if the sample data actually needs to be swapped or not

sample.starttime = CFSwapInt32BigToHost(sample.starttime);
sample.endtime = CFSwapInt32BigToHost(sample.endtime);

从Little Endian更改为Big Endian的行为经常被称为“Byte Swapping” - 您需要知道当前CPU使用的字节顺序(理论上可以根据您的硬件目标进行更改) - 使用iOS,两者都有模拟器(x86)和设备(ARM)都是相同的(Little Endian)。

由于您提到使用Apple Framework,我建议您使用Apple的CoreFoundation功能来完成您的工作。

https://developer.apple.com/library/ios/documentation/CoreFoundation/Conceptual/CFMemoryMgmt/Tasks/ByteSwapping.html