如何获取Int并将其更改为二进制数



我正试图弄清楚如何获得Int并将其更改为具有16位的二进制格式数字。这是16个比特,每个比特可以是0或1。也许得到一个Int并返回一个包含16个元素的数字数组,或者一个长度为16的字符串??我感谢您的反馈。

您可以将这两个答案结合起来:

将Int转换为字节数组

将字节(即UInt8(转换为位

TLDR;


enum Bit: UInt8, CustomStringConvertible {
case zero, one
var description: String {
switch self {
case .one:
return "1"
case .zero:
return "0"
}
}
}
func byteArray<T>(from value: T) -> [UInt8] where T: FixedWidthInteger {
withUnsafeBytes(of: value.bigEndian, Array.init)
}
func bits(fromByte byte: UInt8) -> [Bit] {
var byte = byte
var bits = [Bit](repeating: .zero, count: 8)
for i in 0..<8 {
let currentBit = byte & 0x01
if currentBit != 0 {
bits[i] = .one
}
byte >>= 1
}
return bits
}
// Testing
let value: Int32 = -1333
let bits = withUnsafeBytes(of: value.bigEndian, Array.init)
.flatMap(bits(fromByte:))
print(bits)

最新更新