hoho5702
hoho5702

Reputation: 13

How can I extract bits in Risc v assembly code

Register x5 stores 0x00C0_C000, register x6 stores 0x0000_C0000. At this time, you want to extract the value of bit [15:8] of thte register x5 and put it in the bit [31:16] of the register x6,. Complete the RISC-V assembly code to do this. However, the other bits of x5 and x6 should not change.

Replace the x6 [31:16] bit with the 8bit of [15:8] in the x5 register, but align the 8bit with the lower bit of the [31:16] bit.

I thought I should use slli and srli to extract bit. But using them, the other bit of x5 and x6 changes. How can I extract bits without changing other bits?

Upvotes: 1

Views: 5402

Answers (2)

yflelion
yflelion

Reputation: 1746

What you want to do is: Clearing the high part of x6 if it is not sure it is all the time equal to 0. You can do it with a mask :

li x28,0xffff
and x6,x6,x28

or

slli x6,x6,16
srli x6,x6,16

Since you cannot modify x5, you need to use an other tmp register:

mv x28,x5

get the 8 from [15:8] bits and place them in [31:16]

srli x28,x28,8
andi x28,x28,0xff
slli x28,x28,16

and finally you do an or to place these bits in x6:

or x6,x6,x29

Try also to take a look to https://raw.githubusercontent.com/riscv/riscv-bitmanip/master/bitmanip-0.90.pdf. RISC-V Bitmanip Extension can be interesting if it is supported.

Upvotes: 2

Alexy Khilaev
Alexy Khilaev

Reputation: 444

I would offer a next solution,i am using 0x00debc00 for easier viewing: For RV64I

lui a1,0xDEB     # loads 0x00deb of 0x00debc00
li a2,0xC00      # loads 0xc00 of 0x00debc00
add a1,a1,a2     # stick together 0x00deb + c00 = 0x00debc00
slli a3,a1,48    # took 0x00de"bc"00 and moves to left corner to clean unnecessary bits
srli a4,a3,48    # move "bc" back into 0xbc00
xor a1,a1,a4     # use 0xbc00 for masking initial 0x00debc00 and get 0x00de0000
srli a3,a3,32    # move 0xbc from left corner of $a3 to it's place 0x0000bc00
add a1,a1,a3     # concatenate it all - voila! 0xbcde0000

maybe simpler, but I'm not a magician yet)

For RV32I you just should less shifting to the left:

lui a1,0xDEB
li a2,0xC00
add a1,a1,a2
slli a3,a1,16
srli a4,a3,16
xor a1,a1,a4
#srli a3,a3,32 no need to move back its already in it's place
add a1,a1,a3

Sorry for "Engrish".

Upvotes: 0

Related Questions