我正在尝试将UInt16转换为位数组,我从哪里开始?
我需要将UInt16转换为数组,以便可以移位位。例如,向右移动1110等于2等于1011,或者如果我这样做
var i: UInt16 = 5
i = i >> 3
它将返回0,但是我希望它返回40960。在二进制文件中,它将类似于
0000000000000101 >> 3 = 1010000000000000 (40960)
我不知道从哪里开始这个问题,所以我们将不胜感激
答案 0 :(得分:1)
您可以这样旋转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
答案 1 :(得分:1)
您可以定义一个新的移位运算符,它定义“环绕”或二进制旋转,如下所示:
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
}
}
然后像普通的移位运算符一样使用它:
UInt16(5) >>& 3 // 40960
UInt8(128) <<& 1 // 1
UInt8(128) << 1 // 0