Swift iOS XOR 与从 UInt8 到 Int 的转换
Swift iOS XOR with a conversion from UInt8 to Int
这段代码让我抓狂,它很简单但无法正常工作。我遵循了几个示例并从论坛获得了帮助,但 XOR 不起作用。问题是当我从字符串数组中提取 char 并将其转换为 ASCII 值时,它是 Uint8 而不是 Int。所以 XOR 不起作用,我如何将 Uint8 转换为 int?
// Convert the data into the string
for n in 0...7
{
print("Inside the password generator for loop /(n)")
let a:Character = SerialNumber_hex_array[n]
var a_int = a.asciiValue
let b:Character = salt_arrary[n]
let b_int = b.asciiValue
// This does not work as the a_int & b_int are not int !!!
// How to convert the Uint8 to int?
let xor = (a_int ^ b_int)
// This code works
var a1 = 12
var b1 = 25
var result = a1 ^ b1
print(result) // 21
}
要将 UInt8?
转换为 Int
,请使用可用的 Int
初始值设定项:
let a_int = Int(a.asciiValue!)
let b_int = Int(b.asciiValue!)
let xor = (a_int ^ b_int) // compiles
这种直接方法需要强制解包,但我假设十六进制数组如下所示,并且为了安全起见,您的字符已被硬编码。如果不是,请使用 if-else
或 guard
.
安全地解包这些无符号整数
let SerialNumber_hex_array: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
这段代码让我抓狂,它很简单但无法正常工作。我遵循了几个示例并从论坛获得了帮助,但 XOR 不起作用。问题是当我从字符串数组中提取 char 并将其转换为 ASCII 值时,它是 Uint8 而不是 Int。所以 XOR 不起作用,我如何将 Uint8 转换为 int?
// Convert the data into the string
for n in 0...7
{
print("Inside the password generator for loop /(n)")
let a:Character = SerialNumber_hex_array[n]
var a_int = a.asciiValue
let b:Character = salt_arrary[n]
let b_int = b.asciiValue
// This does not work as the a_int & b_int are not int !!!
// How to convert the Uint8 to int?
let xor = (a_int ^ b_int)
// This code works
var a1 = 12
var b1 = 25
var result = a1 ^ b1
print(result) // 21
}
要将 UInt8?
转换为 Int
,请使用可用的 Int
初始值设定项:
let a_int = Int(a.asciiValue!)
let b_int = Int(b.asciiValue!)
let xor = (a_int ^ b_int) // compiles
这种直接方法需要强制解包,但我假设十六进制数组如下所示,并且为了安全起见,您的字符已被硬编码。如果不是,请使用 if-else
或 guard
.
let SerialNumber_hex_array: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]