我才刚刚开始快速发展。我在Java中有以下方法:
public static byte[] addChecksum(byte[]command, boolean isDeviceSendFormat) {
int checksum = 0;
int l = command.length;
for (int i=0; i<l-2; i++) {
if (i==1 && isDeviceSendFormat==true) {
continue;
}
int val = command[i];
if (val < 0) {
val = 0x100 + val;
}
checksum += val;
}
if (l > 2) {
if (isDeviceSendFormat == false) {
command[l - 1] = (byte) (checksum % 0x100); // LSB
command[l - 2] = (byte) (checksum / 0x100); // MSB
}
else {
command[l - 2] = (byte) (checksum % 0x100); // LSB
command[l - 1] = (byte) (checksum / 0x100); // MSB
}
}
return command;
}
我需要翻译成Swift,我遇到了一些问题,以下是我目前得到的信息:
func addCheckSum(bufferInput:[UInt8], isDeviceSendFormat: Bool) -> [UInt8]{
var checksum: UInt8 = 0
var length: Int = 0
var iIndex: Int
var bufferOutput: [UInt8]
length = bufferInput.count
for (index, value) in bufferInput.enumerated() {
if index < bufferInput.count - 2 {
if value == 1 && isDeviceSendFormat {
continue
}
var val:UInt8 = bufferInput[index]
if (val < 0) {
val = 0x100 + val //Error line
}
checksum = checksum + val
}
}
}
但我得到以下错误:
Integer literal '256' overflows when stored into 'UInt8'
在上面代码的注释行上。如何将此方法从Java转换为Swift?