Dev1234
Dev1234

Reputation: 11

hex to binary code error?

So, i am trying to do a conversion with any value of the hexadecimal to binary but it seems my code doesn't accept 2f and etc. What am i doing wrong?

@IBOutlet weak var input: UITextField!

@IBOutlet weak var mylabel: UILabel!

override func viewDidLoad() {

    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {

    super.didReceiveMemoryWarning()
}

@IBAction func getresults(_ sender: Any) {
    if Int(input.text!,radix:16) != nil
        let hex = String(Int(input.text!,radix:16)!, radix:2)
        mylabel.text = "The Hexadecimal of \(input.text!) conversion is:  \(hex)"
    }else{
        mylabel.text = "Wrong input"

    }
}

Upvotes: 1

Views: 76

Answers (2)

Fogmeister
Fogmeister

Reputation: 77631

I would change your function to this... (I have also changed some variable names as they are currently a bit confusing)

@IBAction func getresults(_ sender: Any) {
    if let inputText = input.text, // 1
       let inputHex = Int(inputText, radix: 16) { // 2

        let binary = String(inputHex, radix: 2) // 3
        mylabel.text = "The Hexadecimal of \(inputText) conversion is:  \(binary)"
    }else{
        mylabel.text = "Wrong input"
    }
}
  1. check that the input is not nil.

  2. convert the input into a hex Int.

If any of the above fail show "Wrong input".

  1. Convert the hex int into binary.

Then display the binary.

Using force unwrapping ! is not recommended as it will crash your app if the value is nil. Using if let (optional binding) is a way to check if it is nil and bind the value to a non-optional variable instead.

Upvotes: 2

Russell
Russell

Reputation: 5554

The first thing you check

if Int(input.text!) != nil

is to see if the input text is a valid integer - and it's not if it includes 2f

Instead of checking for a valid integer, you should check for valid hex

if Int(input.text!,radix:16) != nil

Upvotes: 0

Related Questions