Home > Blockchain >  Swift iOS XOR with a conversion from UInt8 to Int
Swift iOS XOR with a conversion from UInt8 to Int

Time:03-08

This is code has been driving me crazy, it's so simple but cannot get it to work. I have followed several examples and help from the forum, but the XOR is not working. The problem is when I extract the char from the string array and convert it to an ASCII value it's a Uint8 rather than an Int. So the XOR does not work, how can I convert an Uint8 to an 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
                        }

CodePudding user response:

To convert your UInt8? to Int, use an available Int initializer:

let a_int = Int(a.asciiValue!)
let b_int = Int(b.asciiValue!)
let xor = (a_int ^ b_int) // compiles

This direct approach requires force unwrapping but I assume the hex array looks like below and your characters are hard coded for safety. If not, unwrap these unsigned integers safely with if-else or guard.

let SerialNumber_hex_array: [Character] = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
  • Related