这是OC中的代码

我很难将其转换为快速的,尤其是校验和部分的计算

如果有人会写,请告诉我。谢谢。

OC代码:

MessageToOnboard {
unsigned char header[2];
 ushort length;
 uint8_t msgID;
 uint missionID;
 ushort wayPointID;
 double lon;
 double lat;
 float height;
 unsigned char wayPointAction;
//     unsigned long reserve;
 unsigned char checkSum;

}

MessageToOnboard message;
message.header[0] = 'Q';
message.header[1] = 'Z';
message.msgID = 0x21;
message.missionID = 12;
message.wayPointID = 10;
message.lon = 34.2323242;
message.lat = 68.2121221;
message.height = 30;
message.wayPointAction = '2';
message.length = sizeof(message) -5;

uint8_t *msgBIn = (uint8_t *)&message;
int iLength = sizeof(message);
uint8_t icheckSum = 0;
for (int i = 0 ; i < iLength - 3; i++)
{
    icheckSum += *(msgBIn+2+i);
}

message.checkSum = icheckSum;

NSData *data = [[NSData alloc] initWithBytes:&message length:sizeof(message)];


SWIFT代码:
我试过了,但这是不对的,我不知道如何使用指针快速计算结构的总字节数

let msgBIn = withUnsafePointer(to: &message) {$0}
print(msgBIn.pointee)
let iLength: Int = MemoryLayout<MessageToOnboard>.size
let icheckSum: UInt8 = 0
for i in 0..<iLength - 1 {

  let pointer = msgBIn.advanced(by: 2 + i)
  icheckSum += UInt8(pointer)
}

最佳答案

终于解决了这个问题

消息是结构

func sumByte(msg: inout Message) -> UInt8 {

    let pointer = withUnsafePointer(to: msg) {UnsafeRawPointer($0)}
    var sum: UInt8 = 0;
    for i in 0..<(MemoryLayout<Message>.size) {
        let nextP = pointer.advanced(by: i)
        sum += nextP.load(as: UInt8.self)
    }

    return sum;
}

关于swift - 如何快速计算结构的字节和,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54048692/

10-12 23:35