简体   繁体   中英

How to convert UInt16 to an array of bits

I am trying to convert UInt16 to an array of bits, where do I start?

I need to convert the UInt16 to an array so I can shift bits. For example 1110 shifted to the right by 2 equals 1011, or if i do

var i: UInt16 = 5
i = i >> 3

it will return 0, however I want it to return 40960. In binary this will look like

0000000000000101 >> 3 = 1010000000000000 (40960)

I do not know where to start with this problem, so any help is appreciated

You could rotate the bits of an unsigned 16-bit integer this way :

func rotateLeft(_ n: UInt16, by shift: Int) -> UInt16 {
    let sh = shift % 16

    guard sh != 0 else { return n }

    return n << sh + n >> (sh.signum() * (16 - abs(sh)))
}

let num: UInt16 = 0b0100_0000_0000_0000     //16384
let result1 = rotateLeft(num, by: 2)        //1
let result2 = rotateLeft(num, by: -2)       //4096

let num2: UInt16 = 0b1000_0000_0000_0001    //32769
let result3 = rotateLeft(num2, by: 1)       //3
let result4 = rotateLeft(num2, by: -1)      //49152

You can define a new bit-shifting operator that defines "wrap-around" or rather binary rotation like below:

infix operator <<&
infix operator >>&

extension BinaryInteger {
    static func <<&<RHS:BinaryInteger>(lhs:Self, rhs:RHS) -> Self {
        // Do normal bit shifting
        let shifted = lhs << rhs
        // If the result is 0, do a rotation by shifting in the opposite direction
        // by the maximum number of bits - original rotation
        // otherwise return the regularly shifted value
        return shifted == 0 ? lhs >> (lhs.bitWidth - Int(rhs)) : shifted
    }

    static func >>&<RHS:BinaryInteger>(lhs:Self, rhs:RHS) -> Self {
        let shifted = lhs >> rhs
        return shifted == 0 ? lhs << (lhs.bitWidth - Int(rhs)) : shifted
    }
}

Then use it like the normal bit-shift operators:

UInt16(5) >>& 3 // 40960
UInt8(128) <<& 1 // 1
UInt8(128) << 1 // 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM