-2

I am trying to figure out how to get an Int and change to to a binary format number that has 16 bits. That is 16 bits and each can be 0 or 1. Perhaps getting an Int and returning an array of numbers that has 16 elements, or a string that has the length of 16?? I appreciate any feedback.

Amin
  • 99
  • 5

1 Answers1

0

You can combine these two answers:

Convert Int to bytes array

Convert byte (i.e UInt8) into bits

TLDR; for you


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)
CloudBalancing
  • 1,461
  • 2
  • 11
  • 22