2016-12-11 7 views
1

左に1の数を取得しようとしているIm(ビット16-31)このコードはうまくいくようですが、特定の整数。バイナリ表現の左側にある1の数を数える

例: バイナリで1536が0000 0000 0000 0000 | 0000 0110 0000 0000 そして、左に0を得ることは正しいです。

また、 100000左側のバイナリは0000 0000 0000 0001 であり、結果は1です。これも正しいです。

ただし、 バイナリで1000000000は0011 1011 1001 1010 | 1100 1010 0000 0000 と9の代わりに左側に10 1を得るim

Iveは他の数字もテストしましたが、余分な数もあります。

#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 to mipsからコードが正しいかどうかはわかりません。すべてが間違っている可能性があります。

答えて

0

先頭の0と1の数を数えて1の数を数えるために/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: 
関連する問題