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

来源:互联网 发布:js中的map的使用 编辑:程序博客网 时间:2024/06/15 14:36

>>表示右移,如果该数为正,则高位补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..<bit {

            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

    }

阅读全文
1 0
原创粉丝点击