Arrays 如何将UInt16转换为位数组

Arrays 如何将UInt16转换为位数组,arrays,swift,binary,Arrays,Swift,Binary,我正在尝试将UInt16转换为位数组,从何处开始 我需要将UInt16转换成一个数组,这样我就可以移位位了。例如,1110向右移动2等于1011,或者如果我这样做 var i: UInt16 = 5 i = i >> 3 它将返回0,但我希望它返回40960。在二进制中,这将看起来像 0000000000000101 >> 3 = 1010000000000000 (40960) 我不知道从哪里开始解决这个问题,因此非常感谢您的帮助您可以通过以下方式旋转无符号16位整

我正在尝试将UInt16转换为位数组,从何处开始

我需要将UInt16转换成一个数组,这样我就可以移位位了。例如,1110向右移动2等于1011,或者如果我这样做

var i: UInt16 = 5
i = i >> 3
它将返回0,但我希望它返回40960。在二进制中,这将看起来像

0000000000000101 >> 3 = 1010000000000000 (40960)

我不知道从哪里开始解决这个问题,因此非常感谢您的帮助

您可以通过以下方式旋转无符号16位整数的位:

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
func rotateLeft(n:UInt16,按shift:Int)->UInt16{
设sh=shift%16
guard sh!=0 else{return n}
返回n>(sh.signum()*(16-abs(sh)))
}
让num:UInt16=0b0100\u 0000\u 0000\u 0000//16384
让result1=rotateLeft(num,by:2)//1
让result2=rotateLeft(num,by:-2)//4096
设num2:UInt16=0b1000\u 0000\u 0000\u 0001//32769
设result3=rotateLeft(num2,by:1)//3
设result4=rotateLeft(num2,by:-1)//49152

您可以定义一个新的位移位运算符,该运算符定义“环绕”或二进制旋转,如下所示:

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
    }
}
中缀运算符&
扩展二进制积分器{
静态函数(lhs.bitWidth-Int(rhs)):移位
}
静态函数>>&(左:自,右:右)->自{
设移位=lhs>>rhs
返回移位==0?lhs>&3//40960

UInt8(128)您可以右移位整数,而无需先将其转换为数组。您可以直接在
UInt16
上进行位移位,只需执行
let num:UInt16=16;let shifted=num搜索“按位and运算符”。您可以使用“and”运算符来确定各个位的值。如果我执行“var i:UInt16=5;i=i>>3”它将返回0,但我希望它返回40960。在二进制中,这将看起来像0000000000000 101>>3=1010000000000000(40960)@theDarkLordon您的逻辑有缺陷。位移位不会“环绕”。如果您想定义这样的溢出运算符,您需要自己定义
UInt16(5) >>& 3 // 40960
UInt8(128) <<& 1 // 1
UInt8(128) << 1 // 0