Created
March 17, 2016 16:23
-
-
Save eienf/c024f5384744f25f594f to your computer and use it in GitHub Desktop.
Binary String from Number types
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// toBinary | |
func toBinary<T: UnsignedIntegerType>(value: T) -> String { | |
let str = String(value, radix:2) | |
let size = sizeofValue(value) * 8 | |
let padd = String(count: (size - str.characters.count), repeatedValue: Character("0")) | |
return padd + str | |
} | |
func toBinary<T: _SignedIntegerType>(value: T) -> String { | |
let size = sizeofValue(value) * 8 | |
let signed: IntMax = value.toIntMax() | |
let unsigned: UIntMax = UIntMax(bitPattern: signed) | |
var str = String(unsigned, radix:2) | |
switch str.characters.count { | |
case let count where count > size: | |
str = str[str.startIndex.advancedBy(count-size) ..< str.endIndex] | |
default: | |
let padd = String(count: (size - str.characters.count), repeatedValue: Character("0")) | |
str = padd + str | |
} | |
return str | |
} | |
func toBinary<T: FloatingPointType>(value: T) -> String { | |
let size = sizeofValue(value) | |
if size == sizeof(UInt32) { | |
let unsigned = unsafeBitCast(value, UInt32.self) | |
let str = String(unsigned, radix:2) | |
let padd = String(count: (size*8 - str.characters.count), repeatedValue: Character("0")) | |
return padd + str | |
} else if size == sizeof(UInt64) { | |
let unsigned = unsafeBitCast(value, UInt64.self) | |
let str = String(unsigned, radix:2) | |
let padd = String(count: (size*8 - str.characters.count), repeatedValue: Character("0")) | |
return padd + str | |
} | |
return "" | |
} | |
func toBinary(value: Bool) -> String { | |
if sizeofValue(value) == sizeof(UInt8) { | |
let unsigned = unsafeBitCast(value, UInt8.self) | |
let str = String(unsigned, radix:2) | |
let padd = String(count: (8 - str.characters.count), repeatedValue: Character("0")) | |
return padd + str | |
} | |
return "" | |
} | |
func toBinary(value: Character) -> String { | |
let size = sizeofValue(value) | |
return "" | |
} | |
print(toBinary(UInt8(10))) // 00001010 | |
print(toBinary(UInt8(255))) // 11111111 | |
print(toBinary(Int8(10))) // 00001010 | |
print(toBinary(Int8(-1))) // 11111111 | |
print(toBinary(Float(0.5))) // 00111111000000000000000000000000 | |
print(toBinary(Float(-2.0))) // 11000000000000000000000000000000 | |
print(toBinary(true)) // 00000001 | |
print(toBinary(false)) // 00000000 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment