代码之家  ›  专栏  ›  技术社区  ›  AesSedai101

Kotlin'shl'不工作

  •  1
  • AesSedai101  · 技术社区  · 7 年前

    我正在尝试申请 shl Int Kotlin值:

    val a = 1092455
    println(a.toString())
    println(toString(bits(one)))
    println(toString(bits(one shl 16)))
    println(toString(bits(one shr 16)))
    

    这将产生以下输出:

    1092455
    0000000000010000 1010101101100111
    0000000000000000 0000000000000000
    0000000000000000 0000000000010000 
    

    正如你所见, shr 正确生成最左边的16位( 0000000000010000 )然而,被右移 shl公司 未给出预期输出( 1010101101100111 0000000000000000 ).

    我错过了什么?

    编辑: bits 方法:

    fun bits(value: Int): BooleanArray {
        var x = value.toDouble()
        val result = BooleanArray (32)
    
        for (i in 31 downTo 0) {
            val d = Math.pow(2.0, i.toDouble())
            if (x >= d) {
                x -= d
                result[i] = true
            }
        }
    
        return result
    }
    
    1 回复  |  直到 7 年前
        1
  •  4
  •   voddan    7 年前

    数值在Kotlin中签名,当您左移时,值溢出为负数。然后实施 bits 您正在使用的无法正确打印位。

    以下是它对我的作用:

    val a = 1092455
    println((a shr 16).toString(2))
    println((a shl 15).toString(2))
    println((a shl 16).toString(2))
    

    打印:

     10000
     1010101101100111000000000000000
    -1010100100110010000000000000000
    

    这对我来说似乎很合理。

    修复代码使用 Long 值:

    val a: Long = 1092455