How can I multiply and divide using only bit shifting and adding?

后端 未结 14 1637
清歌不尽
清歌不尽 2020-11-22 15:09

How can I multiply and divide using only bit shifting and adding?

相关标签:
14条回答
  • 2020-11-22 15:50

    This should work for multiplication:

    .data
    
    .text
    .globl  main
    
    main:
    
    # $4 * $5 = $2
    
        addi $4, $0, 0x9
        addi $5, $0, 0x6
    
        add  $2, $0, $0 # initialize product to zero
    
    Loop:   
        beq  $5, $0, Exit # if multiplier is 0,terminate loop
        andi $3, $5, 1 # mask out the 0th bit in multiplier
        beq  $3, $0, Shift # if the bit is 0, skip add
        addu $2, $2, $4 # add (shifted) multiplicand to product
    
    Shift: 
        sll $4, $4, 1 # shift up the multiplicand 1 bit
        srl $5, $5, 1 # shift down the multiplier 1 bit
        j Loop # go for next  
    
    Exit: #
    
    
    EXIT: 
    li $v0,10
    syscall
    
    0 讨论(0)
  • 2020-11-22 15:52

    X * 2 = 1 bit shift left
    X / 2 = 1 bit shift right
    X * 3 = shift left 1 bit and then add X

    0 讨论(0)
提交回复
热议问题