【发布时间】:2018-02-18 12:12:07
【问题描述】:
我才刚刚开始涉足 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?
【问题讨论】:
-
你为什么使用
UInt8? Java 的byte已签名,所以Int8不是更好的选择吗? -
@Sweeper 我看到的东西在 Swift 中用于这样的任务,例如这里:bacpeters.com/2017/05/17/crc-16-in-swift-3-x 或这里:github.com/krzyzanowskim/CryptoSwift/blob/master/Sources/…。但这就是问题的重点,也许 Int8 更好,但我不知道。这就是我在这里向专家寻求帮助的原因。