【问题标题】:Counting the number of 1's on the left side of a binary representation计算二进制表示左侧的 1 的数量
【发布时间】:2016-12-11 00:18:16
【问题描述】:

我试图获取左侧 1 的数量(第 16-31 位) 此代码似乎有效,但我从某些整数中获得了 1 的额外计数。

例如: 二进制的 1536 是 0000 0000 0000 0000 | 0000 0110 0000 0000 我在左侧得到 0 1,这是正确的。

还有: 100000 左侧二进制是 0000 0000 0000 0001 我的结果是 1。这也是正确的。

但是: 1000000000 二进制是 0011 1011 1001 1010 | 1100 1010 0000 0000 我在左侧得到 10 个 1 而不是 9 个。

我也测试了其他数字,但它们也有额外的计数。

#Displays number of 1's on left half
   li $v0, 4
   la $a0, left
   syscall

   li $t2, 0 #i = 0
   srl $t3, $s0, 16 #shifts users number to the right by 16 bits

Counter:   
   and $t4, $t3, 1 #Mask off bit
   beq $t4, 1, Count #if mask = 1 go to count
   srl $t3, $t3, 1 #if mask != 1 (aka 0) shifts right by 1

   beq $t3, 0, Exit #once the shifted bits = 0 go to exit

Count:     
   add $t2, $t2, 1 #increment i++
   srl $t3, $t3, 1 #shifts right by 1
   j Counter       

Exit:      
   li $v0, 1 #Displays number of 1's
   move $a0, $t2
   syscall

不确定代码是否正确,因为我是 mips 新手。可能整个事情都错了。

【问题讨论】:

    标签: mips


    【解决方案1】:

    您可以使用clz/clo 来计算前导零和一的数量,并使用它来计算一的数量。这个想法是消耗前导零,然后计算前导零(将这些位移出寄存器),直到输入数据为零。

    即:

      li $t1, 0x4F044321  % $t1 Input number
      srl $t1, $t1, 16
      sll $t1, $t1, 16    % Discard least significant bits
      li $t2, 0           % $t2 will hold number of 1s
    count:
      beqz $t1, done    
      clz $t3, $t1
      sllv $t1, $t1, $t3
      clo $t3, $t1
      addu $t2, $t2, $t3
      sllv $t1, $t1, $t3
      b count
    done:
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2011-12-18
      • 2017-02-13
      • 1970-01-01
      相关资源
      最近更新 更多