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?
You can convert the decimal value to a human-readable binary representation using the
String
initializer that takes aradix
parameter:If you wanted to, you could also pad it with any number of zeroes pretty easily as well:
There is no difference between binary and decimal numeral systems, when you're working with variables until you want to visualize them or if you want to convert types which can hold different ammount of bits.
In your case is enough to write
But this will crash (overflow happens) if
decimal
will hold a value more than 255, because it is maximum value whichUInt8
can hold.Depending on what you want to achieve you can write
You'll get
0
as a result, because this initializer will truncate less significant bits.Second option is
This initializer returns
nil
result instead of crashing, if overflow happens.P.S. If you want to see binary string representation use
Went through a lot of answers on this post but I wonder why haven't anyone mentioned the API
leadingZeroBitCount
on FixedWidthIntegerThis returns the number of zeros in specific UInt eg:
Swift Version
USAGE
UNDER THE HOOD
I modified your version to Swift 2.0 count on strings and added a length check:
Most answers here forget to account for 0, and outputs a representation there is too long.
Based on the answer by @karwag I present:
I modified someone's version to swift 3.0 used the correct initializer for creating a string with repeated values