我才开始进入Swift开发阶段。我在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?
答案 0 :(得分:3)
这是我从Java代码到Swift的翻译:
public static func addChecksum(_ command: inout [UInt8], isDeviceSendFormat: Bool) -> [UInt8] {
var checksum: UInt32 = 0
let l: Int = command.count
for i in 0..<l-2 {
if i == 1 && isDeviceSendFormat {
continue
}
let val = UInt32(command[i])
//No need to modify `val` as it takes non-negative value when `command` is `[UInt8]`.
checksum += val
}
if l > 2 {
if !isDeviceSendFormat {
command[l - 1] = UInt8(checksum % 0x100) // LSB
command[l - 2] = UInt8(truncatingIfNeeded: checksum / 0x100) // Next to LSB
} else {
command[l - 2] = UInt8(checksum % 0x100) // LSB
command[l - 1] = UInt8(truncatingIfNeeded: checksum / 0x100) // Next to LSB
}
}
return command
}
//Assuming `command` is not too long as to make integer overflow in `checksum += val`.
一些注意事项:
Java代码的这三行:
if (val < 0) {
val = 0x100 + val;
}
当0x100
为负时,通过添加256
(= val
)将值-128 ... 127转换为0 ... 255。因此,val
取0到255之间的任何值,因此,我为[UInt8]
选择command
。当您选择UInt8
时,Swift中不需要Java中的3行。
在您的Swift代码中,您为UInt8
和checksum
选择了val
,但Java中的int
为32位长,我选择了{{ 1}}对他们来说。假设整数溢出可能永远不会发生,它们只采用非负值,因此非负32位长整数是合适的。
在Swift中没有直接等同于UInt32
的Java。因此,在某些情况下,byte[]
比[UInt8]
更合适。您可以找到许多将Java [Int8]
翻译成Swift byte[]
的案例。