I need a way to convert a string that contains a literal string representing a hexadecimal value into a Character corresponding to that particular hexadecimal value.
Ideally, something along these lines:
let hexString: String = "2C"
let char: Character = fromHexString(hexString)
println(char) // prints -> ","
I've tried to use the syntax: "\u{n}" where n is a Int or String and neither worked.
This could be used to loop over an array of hexStrings like so:
var hexArray = ["2F", "24", "40", "2A"]
var charArray = [Character]()
charArray = map(hexArray) { charArray.append(Character($0)) }
charArray.description // prints -> "[/, $, @, *]"
Another simple way based on ICU transforms:
Usage:
Results in:
,
Here you go:
BTW, you can include hex values in the literal strings like this:
With Swift 5, you will have to convert your string variable into an integer (using
init(_:radix:)
initializer), create Unicode scalar from this integer (usinginit(_:)
) then create a character from this Unicode scalar (using init(_:)
).The Swift 5 Playground sample code below shows how to proceed:
If you want to perform this operation for the elements inside an array, you can use the sample code below:
Alternative with no force unwraps:
A couple of things about your code:
You don't need to create an array and then assign the result of the map, you can just assign the result and avoid creating an unnecessary array.
Here you can use
hexArray.map
instead ofmap(hexArray)
, also when you use a map function what you are conceptually doing is mapping the elements of the receiver array to a new set of values and the result of the mapping is the new "mapped" array, which means that you don't need to docharArray.append
inside the map closure.Anyway, here is a working example:
EDIT: This is another implementation that doesn't need Foundation:
EDIT2 Yet another option:
Final edit: explanation
Given that the ascii table has all the number together (012345679), we can convert 'N' (base 10) to an integer knowing the ascii value of 0.
Because:
Then if for example you need to convert '9' to 9 you could do
And you can do the same from 'A' to 'F':
Now we can do the same as before but, for example for 'F' we'd do:
Note that we need to add 10 to this number to get the decimal. Then (going back to the code): If the scalar is between A-Z we need to do:
which is the same as:
10 + scalar.value - 65
And if it's between 0-9:
which is the same as:
scalar.value - 48
For example: '2F'
'2' is 2 and 'F' is 15 (by the previous example), right?. Since hex is base 16 we'd need to do:
((16 ^ 1) * 2) + ((16 ^ 0) * 15) = 47