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

How would I convert this data from Little Endian to Big Endian

我正在开发一种以小端格式输出数据的解决方案,我需要将其转换为 objective-c,解决此问题的最佳方法是什么。

从概念上讲,我明白发生了什么,我正在努力编写实现它的代码。

数据正在 CBCharacteristic 中输出。

更新:

- (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 纪元。

根据您上面的示例,您似乎正在从某个设备读取一些数据——并且这些数据被打包在一个 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 使用的字节顺序(理论上可以根据您的硬件进行更改) target) - iOS,模拟器 (x86) 和设备 (ARM) 都是相同的 (Little Endian)。

既然您提到使用 Apple 框架,我建议您使用 Apple 的 CoreFoundation 函数来完成您的工作。

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