How can I convert Int to UInt8 in Swift? Example. I want to convert number 22 to 0b00010110
var decimal = 22
var binary:UInt8 = ??? //What should I write here?
How can I convert Int to UInt8 in Swift? Example. I want to convert number 22 to 0b00010110
var decimal = 22
var binary:UInt8 = ??? //What should I write here?
Swift 5.1 / Xcode 11
Thanks Gustavo Seidler. My version of his solution is complemented by spaces for readability.
Examples:
If you want
binary
to have the value of22
, just assign it that:binary = 22
or you could write it asbinary = 0b00010110
; the two statements are equivalent.swift 4.1
result
15 00001111
240 11110000
good for you~
Here's how I would do it:
Since none of the solutions contemplate negative numbers, I came up with a simple solution that basically reads the number's internal representation and pads it automatically to the width of its type. This should work on all
BinaryInteger
types.Examples:
So I had this come up recently. The other generic solutions didn't work for me, due to various issues. Anyway, here's my solution (Swift 4):
Tests: