Let say we can mark weekend day active or inactive. I need to use Integer to say system that I marked day active or inactive, to retrieve this integer I need to use array [1, 1, 1, 1, 1, 1, 1]
. So if you see at this array all day of week marked as active and in Hexadecimal it's 0000007F
.
If I use [0, 0, 0, 0, 0, 0, 1]
this string it means Hexadecimal = 00000001
. So my question is how to create Hexadecimal from array and then get form it an Integer
. So in case with 0000007F
it should be 127.
I assume that it should be something like that:
let array = [1, 1, 1, 1, 1, 1, 1] let hexadecimal = array.toHexadecimal let intNumber = hexadecimal.toInt
print(intNumber) // prints 127
Also I guess it can be for example an array with ints like [0, 1, 1, 1, 1, 0, 1] which means that Monday and from Wednesday till Saturday (including) are active days.
You can use reduce method to sum up your binary array (inspired at this answer) and use String(radix:) initializer to convert your integer to hexa string:
Swift 3 • Xcode 8 or later
let binaryArray = [1, 1, 1, 1, 1, 1, 1]
let integerValue = binaryArray.reduce(0, {$0*2 + $1})
let hexaString = String(integerValue, radix: 16) // "7f"