Swift native functions to have numbers as hex strings
As of Swift 2, all integer types have a constructor
init?(_ text: String, radix: Int = default)
so that both integer
to hex string and hex string to integer conversions can be done
with built-in methods. Example:
let num = 1000
let str = String(num, radix: 16)
print(str) // "3e8"
if let num2 = Int(str, radix: 16) {
print(num2) // 1000
}
(Old answer for Swift 1:) The conversion from an integer to a hex string can be done with
let hex = String(num, radix: 16)
(see for example How to convert a decimal number to binary in Swift?). This does not require the import of any Framework
and works with any base between 2 and 36.
The conversion from a hex string to an integer can be done with the BSD
library function strtoul()
(compare How to convert a binary to decimal in Swift?) if you are willing to import Darwin
.
Otherwise there is (as far as I know) no built-in Swift method. Here is an extension
that converts a string to a number according to a given base:
extension UInt {
init?(_ string: String, radix: UInt) {
let digits = "0123456789abcdefghijklmnopqrstuvwxyz"
var result = UInt(0)
for digit in string.lowercaseString {
if let range = digits.rangeOfString(String(digit)) {
let val = UInt(distance(digits.startIndex, range.startIndex))
if val >= radix {
return nil
}
result = result * radix + val
} else {
return nil
}
}
self = result
}
}
Example:
let hexString = "A0"
if let num = UInt(hexString, radix: 16) {
println(num)
} else {
println("invalid input")
}
How to convert an Int to Hex String in Swift
You can now do:
let n = 14
var st = String(format:"%02X", n)
st += " is the hexadecimal representation of \(n)"
print(st)
0E is the hexadecimal representation of 14
Note: The 2
in this example is the field width and represents the minimum length desired. The 0
tells it to pad the result with leading 0
's if necessary. (Without the 0
, the result would be padded with leading spaces). Of course, if the result is larger than two characters, the field length will not be clipped to a width of 2
; it will expand to whatever length is necessary to display the full result.
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 macOS programming.
Use uppercase X
if you want A...F
and lowercase x
if you want a...f
:
String(format: "%x %X", 64206, 64206) // "face FACE"
If you want to print integer values larger than UInt32.max
, add ll
(el-el, not eleven) to the format string:
let n = UInt64.max
print(String(format: "%llX is hexadecimal for \(n)", n))
FFFFFFFFFFFFFFFF is hexadecimal for 18446744073709551615
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 the hexadecimal representation of \(n)"
// "7B is the hexadecimal representation of 123"
Cant convert string hex into hexint and then into UIColor
You have to remove the 0x
prefix and then specify the radix 16:
let s = "0xe7c79d"
print(Int(s)) // nil
let value = s.hasPrefix("0x")
? String(s.dropFirst(2))
: s
print(Int(value, radix: 16)) // 15189917
Swift native formatting in numeric bases
I read the conversation more closely and it was the 'num' label that broke it. If I use String(123, radix: 16) it works fine. Fractions do NOT work, however. I got a runtime error with String(123.55, radix: 16).
EDIT: As nhgrif points out below, this is now a compiler error, not a runtime error - so it should have never been allowed. This is true as of XCode Version 7.1.1 (7B1005). I believe what is going on is with the num: label on the first parameter it is creating a tuple, then calling the String initializer which converts the tuple to it's string representation. I personally would have expected that to look like this:
let str = String((num: 1, radix: 2));
Which the compiler treats the same way (same result output).
Making a table of hex representations in Swift with compact code
Yes there is. The approach is the same: map each number in the range
0 ... 255 to a string using a hex format:
let hexTable = (0 ..< 256).map { v in String(format: "%02X", v) }
or slightly shorter:
let hexTable = (0 ..< 256).map { String(format: "%02X", $0) }
Result:
["00", "01", "02", ..., "FD", "FE", "FF"]
swift: hexdecimal string to double
Get the integer value from hex string with Int(_:radix:)
let string = "ff14"
let hexValue = Int(string, radix: 16)!
and divide by 65535 (16 bit) to get values between 0.0 and 1.0
let result = Double(hexValue) / 65535
Related Topics
How to Convert an Nsstring Value to Nsdata
Uiwebview: Html5 Audio Pauses in iOS 6 When App Enters Background
Getting iOS System Uptime, That Doesn't Pause When Asleep
How to Add Image and Text in Uitextview in Ios
Enabling Auto Layout in iOS 6 While Remaining Backwards Compatible With iOS 5
Swrevealviewcontroller Without Using Navigationcontroller
How to Use Generic Protocol as a Variable Type
Swift 3.1 Deprecates Initialize(). How to Achieve the Same Thing
Arm64 Architecture in Xcode 5.1
What Kind of Leaks Does Automatic Reference Counting in Objective-C Not Prevent or Minimize
Uitableviewcell, Show Delete Button on Swipe
Sending Data With Segue With Swift
Enterprise App Update Distribution on iOS 8
How to Set the Width of a Cell in a Uitableview in Grouped Style