boscarol boscarol - 4 years ago 1554
Swift Question

How to convert an Int to Hex String in Swift

In Obj-C I used to convert an unsigned integer n to a hex string with

NSString *st = [NSString stringWithFormat:@"%2X", n];


I tried for a long time to translate this into Swift language, but unsuccessfully.

Can anyone help me?

Thank you.

Answer Source

You can now do:

let n = 123
var st = String(format:"%2X", n)
st += " is \(n) in hex"
// "7B is 123 in hex"

This only works if you have Foundation imported (this includes the import of Cocoa or UIKit). This isn't a problem if you're doing iOS or OS X programming.


Original Answer

You can still use NSString to do this. The format is:

var st = NSString(format:"%2X", n)

This makes st an NSString, so then things like += do not work. If you want to be able to append to the string with += make st into a String like this:

var st = NSString(format:"%2X", n) as String

or

var st = String(NSString(format:"%2X", n))

or

var st: String = NSString(format:"%2X", n)

Then you can do:

let n = 123
var st = NSString(format:"%2X", n) as String
st += " is \(n) in hex"
// "7B is 123 in hex"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download