swift3.0无符号右移(类似Java的>>>)

>>表示右移,如果该数为正,则高位补0,若为负数,则高位补1;

>>>表示无符号右移,也叫逻辑右移,即若该数为正,则高位补0,而若该数为负数,则右移后高位同样补0。

以32位为例,参数:value为十进制数,bit为右移的位数,返回结果是一个32位的整数


private func relizeRight(value:Int32, bit: Int32) ->Int32 {

        

        //将十进制转为二进制

        var caculate =String.init(value, radix:2)

        

        if caculate.characters.first =="-" {

            let index = caculate.index(caculate.startIndex, offsetBy:1)

            caculate = caculate.substring(from: index)

        }

        

        for_ in0..<32-caculate.characters.count {


            caculate = "0"+caculate

        }

        

        //如果是负数位移那么要对二进制数取反然后+1

        if value <0 {

            

            let becomeTwo = caculate.replacingOccurrences(of:"1", with: "2")

            let becomeOne = becomeTwo.replacingOccurrences(of:"0", with: "1")

            caculate = becomeOne.replacingOccurrences(of:"2", with: "0")

            

            if caculate.characters.last =="0" {

                

                let index = caculate.index(caculate.startIndex, offsetBy: caculate.characters.count - 1)

                caculate = caculate.substring(to: index)+ "1"

            }else {

               

                let index = caculate.index(caculate.startIndex, offsetBy: caculate.characters.count - 2)

                caculate = caculate.substring(to: index)+ "10"

            }

        }

        

        for_ in0..

            caculate = "0"+caculate

        }

        let index = caculate.index(caculate.startIndex, offsetBy:32)

        caculate = caculate.substring(to: index)


        let myResult =Int32.init(caculate, radix:2)

        

        return myResult ??0

    }

你可能感兴趣的:(swift开发)