Matrosov Alexander - 1 year ago 73
iOS Question

# Swift build hexadecimal from array (active/inactive states) of Int and get an integer form hexadecimal

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]

print(intNumber) // prints 127

Also I guess it can be for example an array with ints like [0, 1, 1, 1, 1, 0, 1] wich 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 2.3 • Xcode 8 GM

``````let binaryArray =  [1, 1, 1, 1, 1, 1, 1]
//
let integerValue = binaryArray.reduce(0, combine: {\$0*2 + \$1})

let hexaString = String(integerValue, radix: 16)  // "7f"
``````

Swift 3 • Xcode 8 GM

``````let binaryArray =  [1, 1, 1, 1, 1, 1, 1]

let integerValue = binaryArray.reduce(0, {\$0*2 + \$1})
let hexaString = String(integerValue, radix: 16)  // "7f"
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download